Type error in createServerValidate when using discriminated union schemas
When using discriminated unions as schemas, the createServerValidate function gives a type error. If I cast the defaultValues in formOptions, the error goes away. Is this the intended approach or is there some more type safe way to use discriminated unions?
Stackblitz: https://stackblitz.com/edit/tanstack-form-tnj3qpfd?file=src%2Findex.tsx
StackBlitz
Form Simple Example (duplicated) - StackBlitz
Run official live example code for Form Simple, created by Tanstack on StackBlitz
10 Replies
ambitious-aqua•2mo ago
The last paragraph should be the solution to your problem
absent-sapphireOP•2mo ago
I updated the stackblitz. Still getting the same error.
fascinating-indigo•2mo ago
doesn't list a type error for me. Which line causes the error for you?

absent-sapphireOP•2mo ago
The type error only appears after typing something in to the editor, seems like a bug with stackblitz. Lines 27-32 turn squiggly
Here's the error:
fascinating-indigo•2mo ago
TypeScript is being too strict with you
what ends up happening is TS thinks "this value never changes, so it's not
z.input<typeof ExampleSchema
, but it's only the foo
variant
really strange. But one way to 'fix' it is to reassign it
absent-sapphireOP•2mo ago
Yeah, what makes this extra weird is that the type definition seems to be the full union when hovering the variable definition but then when hovering the value inside formOptions the type is narrowed down.


fascinating-indigo•2mo ago
yeah, and passing it directly also appears to be the union

fascinating-indigo•2mo ago
so I guess it's an issue with formOptions? deserves some further investigating I reckon
can you create a GH issue for checking generated formOptions types vs. passing directly?
absent-sapphireOP•2mo ago
Sure 👍
fascinating-indigo•2mo ago
I found an issue on TypeScript's repo that appears to address this concern. Marked as not planned :Sadge: https://github.com/microsoft/TypeScript/issues/61789
@Lomant
GitHub
Skip assignment narrowing when declaring & initializing a variable ...
🔍 Search Terms declare, assign, declaration, assignment, narrow, narrowing, union, variable, "control flow analysis" ✅ Viability Checklist This wouldn't be a breaking change in existi...