tanstack form type errors with a zod discriminated union
For context, here is my schema expressed in ts types for clarity In my form the default value of engine_type is 'Petrol", so the 1st variant is used for type checking. I am using the form.Subscribe HOC to show only the relavant fields based on the engine_type. The type error manifests in the electric car only fields. Any idea how to get rid of the type error without casting?
4 Replies
exotic-emerald•2mo ago
how do you give the form the default values?
what might be happening is two things:
1. You're giving the defaultValues directly. TypeScript won't know it can be a union in this case, so it will complain.
2. You're assigning
defaultValues externally with the correct type. However, TypeScript thinks that, since defaultValues is never reassigned, it is only part of the union. It's a problem that has been around for a while, and neither satisfies or as can properly solve it.
conscious-sapphireOP•2mo ago
I use the 2nd approach, external assignment
Satisfies + as combo works 🙂
exotic-emerald•2mo ago
for a quick check,
satisfies X as X should "solve the types"
okay, yeah then it was that issue
as general note, you'll often see this problem pop up with string unions and assigning an initial one. An identity function never hurts to be around for type safety
An example from our workplace:
exotic-emerald•2mo ago
Also the TypeScript repository's issue talking about this: https://github.com/microsoft/TypeScript/issues/61789
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...