Could Zod provide type guards for narrowing union types?
See original GitHub issueI am using v3 branch and would like to ask if it is possible for Zod to provide type guards? This will be handy when dealing with union types:
const ASchema = z.object({a: z.string()});
type A = z.infer<typeof ASchema>;
const BSchema = z.object({b: z.string()});
type B = z.infer<typeof BSchema>;
const ABSchema = z.union([ASchema, BSchema])
const AB = z.infer<typeof ABSchema>; // { a: string } | { b: string}
function f(x: AB) {
if (ASchema.guard(x)) {
x.a // x is A
} else {
x.b
}
}
Issue Analytics
- State:
- Created 2 years ago
- Reactions:1
- Comments:5 (1 by maintainers)
Top Results From Across the Web
colinhacks/zod: TypeScript-first schema validation ... - GitHub
With Zod, you declare a validator once and Zod will automatically infer the static TypeScript type. It's easy to compose simpler types into...
Read more >narrowing types via type guards and assertion functions - 2ality
TypeScript's type inference supports type guards by narrowing the static type of an operand when the result is true .
Read more >Type-Safe TypeScript with Type Narrowing - Rainer Hahnekamp
Whenever we deal with a variable that can be of multiple types, like an unknown or a union type, we can apply type...
Read more >Narrowing Types in TypeScript - Formidable Labs
Type narrowing is just what it sounds like—narrowing down a general type into something more precise. Here's how to do it.
Read more >Understanding the discriminated union pattern
The discriminated union pattern is a way of narrowing a union type. A requirement for this pattern is for the types in the...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
No type guards in Zod@3 due to how they interact with the
transform
feature, however you could definitely do this with parsing:I’ve found that most unions want (or already have!) some kind of discriminant though, so in that case TypeScript is already smart enough to narrow the type if you check the discriminant.
Thanks Scott 👍
@redbaron I propose using a discriminated union for this. It’s the best way to handle unions like this: