Zod 2 - parseAsync breaks unions of objects
See original GitHub issueimport * as z from 'zod';
const Schema = z.union([
z.object({
ty: z.literal('A'),
}),
z.object({
ty: z.literal('B'),
}),
]);
(async () => {
const obj = { ty: 'A' };
console.log(Schema.parse(obj)); // Works
console.log(await Schema.parseAsync(obj)); // Works with 1.11.10, breaks with 2.0.0-beta.21
})();
With Zod 2.0.0-beta.21, the parseAsync
call fails with
{
"code": "invalid_literal_value",
"expected": "B",
"path": [
"ty"
],
"message": "Input must be \"B\""
}
The objects wrapping the literals are important. A schema of z.union([z.literal('A'), z.literal('B')])
worked fine.
Issue Analytics
- State:
- Created 3 years ago
- Reactions:1
- Comments:9 (4 by maintainers)
Top Results From Across the Web
Incorrect error for unions with literals #311 - colinhacks/zod
Basically any union types containing objects seems to yield wrong error messages. Tried with zod@1.11.1 and zod@next . It seems like it builds...
Read more >How to extract a single type from a Zod union type?
After parsing it I want to iterate through each item and extract it's "real" type / cut off the other types. When checking...
Read more >Error Handling in Zod
Discriminated unions are an ideal way to represent a data structures that may be one of many possible variants. You can see all...
Read more >Union declaration - cppreference.com
Two union objects have the same corresponding active member (if any) after construction or assignment via trivial special functions.
Read more >Union Types - JavaScript. Flow
Disjoint unions require you to use a single property to distinguish each object type. You cannot distinguish two different objects by different properties....
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
Looks like there were multiple bugs in play here. I fixed one problem with how objects get parsed but there was another issue with unions. I can confirm the original snippet now runs correctly with beta 25 (and it’s been added to the test suite!).
This is working for me on v2 beta 29. Are you sure you’re using the latest beta?
To answer your other question, I’m planning to skip v2 and release v3 into beta shortly. I recommend using v3 for your project, it’s as stable as v2 since very few changes were made. The only reason its a major version bump is because there are some breaking changes to transformers. v3 will be in beta for a short time (perhaps a month) before a general release.