colinhacks / zod

TypeScript-first schema validation with static type inference
https://zod.dev
MIT License
33.09k stars 1.15k forks source link

Support for all types of discriminators in `z.discriminatedUnion` #3624

Open RichardCPoint opened 2 months ago

RichardCPoint commented 2 months ago

Currently in discriminated unions, the discriminator key must be one of a limited number of literal types (see getDiscriminator).

This change allows any Zod type to be used for the discriminator key

This resolves the following issue:

and also covers other use-cases, e.g. to allow an "anything else" case, where the final discriminator key accepts any value other than the known enum values from the other cases:

Async parsing is supported (and covered by a unit test), with validation of the keys happening in parallel.

At parsing time, if the object being parsed matches more than one discriminator key, the object is considered invalid (previously this could always be checked at type-construction time).

Performance

There is only a performance hit if some of the discriminator keys are not one of the literal types already recognized (in which case all unrecognized keys must be checked one by one). Existing use-cases will have the same performance as before.

netlify[bot] commented 2 months ago

Deploy Preview for guileless-rolypoly-866f8a ready!

Built without sensitive environment variables

Name Link
Latest commit 35335708bb35f8f96238268b77e892918639768f
Latest deploy log https://app.netlify.com/sites/guileless-rolypoly-866f8a/deploys/668ebd4e35f6ec0008b91909
Deploy Preview https://deploy-preview-3624--guileless-rolypoly-866f8a.netlify.app
Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.