T
TanStack7mo ago
harsh-harlequin

Type errors when adding a validator zod schema and initializing the default value to null.

I have a schema where the field month is validated to be non null.
const schema = z.object({ month: z.coerce.date()})
const schema = z.object({ month: z.coerce.date()})
on the form end
const form = useAppForm({
defaultValues: {
month: null
},
validators: {
onSubmit: schema, //type error at the onSubmit because month is 'null'
},
})
const form = useAppForm({
defaultValues: {
month: null
},
validators: {
onSubmit: schema, //type error at the onSubmit because month is 'null'
},
})
I don't want to initialize with a date, since its a MonthPickerInput component. What are the options?
MonthPickerInput | Mantine
Month, multiple months and months range picker input
7 Replies
rival-black
rival-black7mo ago
defaultValues: {
month: null
} as z.infer<typeof schema>
defaultValues: {
month: null
} as z.infer<typeof schema>
harsh-harlequin
harsh-harlequinOP7mo ago
thanks @ksgn 🤦🏼‍♂️ can't believe solution is that simple update, have to use Partial<inferred>, but it works perfectly Follow up question Technically, since I passed the schema to the onSubmit validator, shouldn't value in onSubmit be the inferred type of the Schema and not the default values so i don't have to cast it there?
defaultValues: {
//omitted
} as Partial<NewInitiative>,
validators: {
onSubmit: NewInitiativeSchema,
},
onSubmit: async ({ value }) => {
await mutateAsync(value as NewInitiative);
defaultValues: {
//omitted
} as Partial<NewInitiative>,
validators: {
onSubmit: NewInitiativeSchema,
},
onSubmit: async ({ value }) => {
await mutateAsync(value as NewInitiative);
continuing-cyan
continuing-cyan7mo ago
value is inferred from defaultValues. Why do you pass Partial, do you need them to be typed as Date | undefined? if not, you can just cast the empty object as NewInitiative in defaultValues
harsh-harlequin
harsh-harlequinOP7mo ago
i want month to initialize to null, i don't want the monthpicker to have a preselected value on the form, hence defaultValue for month should be null/undefined On the schema end, i don't want it to be nullable or typed as Date | undefined, i want it to show errors on the form if the user forgets to fill up that field you're right i don't need the Partial when casting the default values, it was my LSP server lagging
wise-white
wise-white7mo ago
What you're looking for is this: https://discord.com/channels/719702312431386674/1100437019857014895/1347536458470264923 But it's a limitation of Zod, bit Form that it doesn't exist ootb
harsh-harlequin
harsh-harlequinOP7mo ago
yeah, just saw that thread. seems to be a common problem? I still think that onSubmit values should be typed to the validators output if it exists
wise-white
wise-white7mo ago
That's the goal eventually; the typing (and runtime code) to support that is non-trivial

Did you find this page helpful?