TanStackT
TanStack9mo ago
20 replies
rubber-blue

Best practice typing a boolean field using zod (or other schema library)

Let's say I have a field in my form where a user has to pick "yes" or "no". There is no default.
Arguably I would use a zod type like so isDogOwner: z.boolean()

Now, if I don't provide a default value in my defaultValues, typescript will complain that it's not matching the schema.
If I make it optional in zod, it will be optional in defaultValues.. but now my form validation is not right since I need the user to make a choice before submitting.

In text fields this is not a problem since you just use an empty string, but what do we do in these scenarios? I feel like something in the typescript implementation is wrong here, my gut is telling me that defaultValues should be a Partial of the schema so you can chose if you shall provide a default or not for a specific field. Thoughts, suggestions?
Was this page helpful?