T
TanStack3w ago
ratty-blush

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;
});
}
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,
},
})
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,
},
})
2 Replies
metropolitan-bronze
metropolitan-bronze3w ago
the helper is one part of it. TypeScript does not know that your defaultValues are z.input<typeof schema> so assigning it outside of the hook is both type safer and actually gives it the type
ratty-blush
ratty-blushOP3w ago
that worked thankyou!

Did you find this page helpful?