zod
zod copied to clipboard
Wrong error when using a union with strict objects
I have two object types with one key each (with different names), and I want to parse an object and verify that it has one and only one of those keys. To do that, I created a union schema with two strict objects:
z.union([
z.object({ a: z.number() }).strict(),
z.object({ b: z.number() }).strict()
])
If I parse { a: 1 } or { b: 1 } it validates successfully as expected, and if I parse { c: 1 } it gives an invalid_union error with the issue from both union elements in unionErrors as expected.
However if I parse { a: 1, b: 1 } I don't get an invalid_union error. I instead get an unrecognized_keys error, i.e. the same error you would get if you parsed this directly with z.object({ a: z.number() }).strict(). I also see that in other to change this error message, I have to add an errorMap to the object schema, rather than the union schema. Since none of the object schemas match the input, I would expect to get an invalid_union here as well.
This makes it hard to get a useful error message for this use case.
It seems like what's happening is that when checking if any of the union schemas is valid, it doesn't consider them to be strict, then selects the first since it matches when it's not strict, and then applies strict afterwards?
This is a nice find, thanks for the detailed reporting and troubleshooting. I think you're right that we should treat this as a union error. I don't have any great ideas right off the top of my head, but PRs definitely welcome for tidying this up!
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.
I opened #872 to fix this a couple of months ago.
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.
Still relevant, the PR hasn't been reviewed.
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.
Still relevant, the PR hasn't been reviewed.
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.
...
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.