T
TanStack3mo ago
inland-turquoise

Zod optional value in schema complains with default value

Hey team, I'm running into an issue where if my zod schema has an optional value in it, and I set that defaultValue then I get a type error. I don't have a reproduction, but if you go to https://tanstack.com/form/latest/docs/framework/react/examples/standard-schema?panel=sandbox and change a value to optional you can see the type error in the sandbox (I've included screen shots). I would have thought that a zod schema that is optional string should allow a default of string and not complain that it could be undefined. I might be missing something though, and I don't want to cast the default values with an as if I can help it...
No description
No description
2 Replies
dependent-tan
dependent-tan3mo ago
the reason is because TypeScript (tries to) protect you from wrongly matching schemas with values. The intended guard is to prevent you from setting properties that don't exist or match against schemas that don't have those properties. However, it also tries to do that with the types, which can get confused if you don't inform TypeScript about your intentions. In this case, you would tell TypeScript that you're typing the defaultValues as a state of the schema:
const defaultValues: z.input<typeof yourSchema> = {
}
// ...
const form = useForm({
defaultValues,
// ...
})
const defaultValues: z.input<typeof yourSchema> = {
}
// ...
const form = useForm({
defaultValues,
// ...
})
the optional tag specifically in zod has some TypeScript issues, mostly because it does not differentiate between
{
foo: string | undefined
}
{
foo: string | undefined
}
and
{
foo?: string
}
{
foo?: string
}
even though those are different in TypeScript. It's always good to extract defaultValues to outside of the form if you're working with complex schemas
inland-turquoise
inland-turquoiseOP3mo ago
Thanks! This makes sense and I'm happy.

Did you find this page helpful?