colinhacks / zod

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

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

Open RichardCPoint opened 4 months ago

RichardCPoint commented 4 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 4 months ago

Deploy Preview for guileless-rolypoly-866f8a ready!

Built without sensitive environment variables

Name Link
Latest commit c5649936cca10726ef63c7041255519ead3b9709
Latest deploy log https://app.netlify.com/sites/guileless-rolypoly-866f8a/deploys/6712a2f0d8ea6a0008dab329
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.