Why is defaultValues required to correctly get type-safety?
More of a question, if I already have a Zod schema defined, why can't tanstack form use the type from that validation instead of requiring me to specify each default value just so I can get type safety?
16 Replies
xenial-black•3mo ago
because the zod schema defines what it expects, and your form doesn't have any values that satisfy zod. That is type safety. Could you give an example of what you mean specifically?
inland-turquoiseOP•3mo ago
but if the form does not satisfy Zod why not just fail the validation then? my form will require user input anyway
xenial-black•3mo ago
rare-sapphire•3mo ago
Wouldn't the field be uncontrolled when no value is passed for it?
https://tanstack.com/form/latest/docs/philosophy#controlled-is-cool
Philosophy | TanStack Form Docs
Every well-established project should have a philosophy that guides its development. Without a core philosophy, development can languish in endless decision-making and have weaker APIs as a result. Th...
inland-turquoiseOP•3mo ago
i still don't get it, why this would not work?
xenial-black•3mo ago
because you have no runtime values to even use
what's the initial state of your form?
inland-turquoiseOP•3mo ago
can't it accept undefined?
xenial-black•3mo ago
see ksgn's comment on uncontrolled values
inland-turquoiseOP•3mo ago
im reading about controlled and uncontrolled values and i'm confused on why this would be uncontrolled
it's not handled by the DOM, also really appreciate your help
xenial-black•3mo ago
Ask React, because this warning should show up if you try to use this:
React likes it if controlled inputs are
''
instead of undefined
because an inputs value
property is ''
when empty, not undefined
inland-turquoiseOP•3mo ago
damn fair enough
thanks
well time to write some defaultValues for all my inputs
xenial-black•3mo ago
if you want zod to be a source of truth, you can write helper functions for it
generating a default value based on what the schema looks like
inland-turquoiseOP•3mo ago
yeah i was thinking of doing that but i've enums on my form and i've no idea on what default enum I would select
rare-sapphire•3mo ago
An empty string should be fine
xenial-black•3mo ago
well, I think in this case zod will type it as the enum so it would reject that
rare-sapphire•3mo ago
Yes, you would have to use a type assertion as well.