-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Incorrect error for unions with literals #311
Comments
I'm having the same issues, without literals. Basically any union types containing objects seems to yield wrong error messages. Tried with Here's another example: import * as zod from zod;
const schema = zod.union([
zod.object({
a: zod.string(),
}),
zod.object({
b: zod.boolean()
})
]);
schema.parse({ b: 'test' }); |
Zod isn't able to guess which schema in the union is most "relevant". This just isn't possible in the general case. It may seem obvious to you that the The real mystery here is why you received a "invalid_literal_value" error. You should have received an "invalid_union" that contains the errors thrown by each schema within the union. @aliksend when I run the code you provided this is the error I get: (this is on Zod 3 so there will be some small discrepancies but the top-level error should be Error: [
{
"code": "invalid_union",
"unionErrors": [
{
"issues": [
{
"code": "invalid_type",
"expected": "string",
"received": "number",
"path": [
"a"
],
"message": "Expected string, received number"
}
]
},
{
"issues": [
{
"code": "invalid_type",
"expected": "b",
"received": "a",
"path": [
"val"
],
"message": "Expected b, received a"
}
]
}
],
"path": [],
"message": "Invalid input"
}
] |
@colinhacks you can use this repl to investigate issue. |
I have been using Zod 3 and poor error messages when using discriminated unions lead me to this issue. As @colinhacks pointed out above Zod isn't able to guess which schema is most "relevant", but has it been considered to add an explicit "discriminated union" construct to Zod? JSON Type Definition has a discriminator form for specifically this purpose, e.g.
There's an AJV implementation as well. In Zod, it could look something like:
If there are no immediate objections I'd be happy to work on an implementation. |
@hmaurer I think this is a very interesting concept. I like that API and I'd be very interested in a PR! |
@hmaurer I'm closing this but if you want to create a separate issue for discriminated unions feel free. |
Any luck with that @hmaurer ? |
I implemented a function for handling discriminated unions (using zod 3.11.6).
More info here: #792 (comment) |
Description
I use
zod@2.0.0-beta.30
I want to use zod to parse structures like
but I get incorrect error when I tries to parse structure with incorrect field's type
Demo
Expected error
Actual error
The text was updated successfully, but these errors were encountered: