Optional fields
Hi guys, I have a question about Tanstack Form.
You can see that email is optional. But when I do it like this, the line
onChange: schema
starts firing an error sayng The types of ''~standard'.types' are incompatible between these types..
What is the best approach to handle optional fields?
Someone suggested casting the default values like this:
But I don't really like casting and I feel like there should be a nicer solution to have some fields optional12 Replies
adverse-sapphire•5mo ago
I don't really like castingme neither but here it's the way to go
other-emerald•5mo ago
satisfies
instead of as
gives you greater type safety
for zod specifically, you can use the fact that input and output are different types to have a better experience with tanstack formwise-whiteOP•5mo ago
Feels weird when of the selling points of Tanstack form was that you don't need to provide generics and yet you need to cast to make it work with optional fields
Nope, satisfies does not help with this error
other-emerald•5mo ago
casting is the short way. You could rewrite to an assertion if that's your major concern:
wise-whiteOP•5mo ago
Connected to this issue - when I remove the default values altogether:
The value inside onSubmit is of type unknown. I would expect it to infer the value based on the result of the validator. Am I doing something wrong or are default values required at all times?
other-emerald•5mo ago
well, the validator ensures that your values match up. Unknown can be any value, so the validator doesn't complain.
defaultValues tell the form how to populate its data, so you should always pass it
wise-whiteOP•5mo ago
Well yes, but sometimes you need some default values to be undefined. I would expect the form lib to infer the types based on the validator function, and not on the default values, as they are many times different from what I want in the output
other-emerald•5mo ago
If the input values are different than your desired output values, that's what zod (and other standard schema libraries) can work well with:
wise-whiteOP•5mo ago
Yes, this proves my point - when I have it like this, the only type that is used is the InputType, and not the OutputType. I would expect that after submit validation, I would have the value being OutputType.
other-emerald•5mo ago
yes, that‘s the current implementation
I think it was because field validators could override form level validators
which could maybe cause conflicts? idk. Point is you get the input type on submit
wise-whiteOP•5mo ago
Shame, It would be so much nicer
other-emerald•5mo ago
well, if you know how to implement it, a PR is always welcome