-
-
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
Discriminated Union based on nested object property? #1868
Comments
I find using superRefine for these more complicated use cases to work well so far. Maybe try something like
|
The fixedValue validation in the zod schema was not incorporated yet. Doing this via the union in zod is not possible because we have nested descriminators, and zod can't figure this out (nor can typescript, to be fair). See colinhacks/zod#1868 for more information.
The fixedValue validation in the zod schema was not incorporated yet. Doing this via the union in zod is not possible because we have nested descriminators, and zod can't figure this out (nor can typescript, to be fair). See colinhacks/zod#1868 for more information.
I need the same nested object property as a discriminator functionality but I get the impression it's still not supported despite all of the discussions in #2106 , yes? |
I was hoping to be able to do something like this: const statusQuerySchema = z.discriminatedUnion("customStatus.stage", [
statusQueryFooResultSuccessSchema,
statusQueryBarResultSuccessSchema,
]); I'm not sure if this is a good way to achieve it, but I was playing around this afternoon and came up with this idea as a hacky workaround; basically using z.preprocess(
(input) => {
if (typeof input !== "object" || input === null) return input;
const result = z
.object({
customStatus: customStatusSchema,
})
.safeParse(input);
if (result.success) {
return {
...input,
_flattenedCustomStatusStage: result.data.customStatus.stage,
_flattenedCustomStatusStatus: result.data.customStatus.status,
};
}
},
z.discriminatedUnion("_flattenedCustomStatusStage", [
statusQueryFooResultSuccessSchema,
statusQueryBarResultSuccessSchema,
]),
); |
@0xdevalias thats a good workaround until there is first-class support. |
Hi there!
I've been playing around with Zod a lot lately and I've been defining a lot of different schemas. When I was reading up on discriminatedUnions, it got me thinking if the following was possible to define in zod:
I could make this property option and use
refine
to check if type is typeA and then enforce id to be present, which is what I am currently going with.However I'd like to define a discriminatedUnion based on the subscription type and then define the event object accordingly.
Is there any way this can be achieved?
e.g
Thanks!
The text was updated successfully, but these errors were encountered: