TanStackT
TanStack3mo ago
3 replies
verbal-lime

NullableInput Helper function not working

I'm trying to use the nullableInput helper function that has been shared a few times

export function nullableInput<TSchema extends ZodTypeAny>(schema: TSchema) {
  return schema.nullable().transform((value, ctx: RefinementCtx) => {
    if (value === null) {
      ctx.addIssue({
        code: z.ZodIssueCode.invalid_type,
        expected: z.getParsedType(schema),
        received: z.ZodParsedType.null,
      });
      return z.NEVER;
    }
    return value;
  });
}


However im still getting an error in my onDynamic validator

Type 'File | null' is not assignable to type 'null'.
Type 'File' is not assignable to type 'null'.

Usage example

const formSchema = z.object({
  xMultiplier: z.coerce.number<string>(),
  yMultiplier: z.coerce.number<string>(),
  xScalarToAdd: z.coerce.number<string>(),
  yScalarToAdd: z.coerce.number<string>(),
  attackerMapImageFile: nullableInput(z.instanceof(File)),
  defenderMapImageFile: nullableInput(z.instanceof(File)),
  showInLineups: z.boolean(),
});

const form = useForm({
    defaultValues: {
      xMultiplier: map?.xMultiplier?.toString() ?? '',
      yMultiplier: map?.yMultiplier?.toString() ?? '',
      xScalarToAdd: map?.xScalarToAdd?.toString() ?? '',
      yScalarToAdd: map?.yScalarToAdd?.toString() ?? '',
      attackerMapImageFile: null,
      defenderMapImageFile: null,
      showInLineups: map?.showInLineups ?? false,
    },
    validationLogic: revalidateLogic(),
    validators: {
      onDynamic: formSchema,
    },
})
Was this page helpful?