Using a union for the discriminator with discriminatedUnions fails #2776
-
Using a union for the discriminator value with discriminatedUnions yields this runtime error:
Sample code: const myUnion = z.discriminatedUnion("status", [
z.object({ status: z.union([z.literal("success"), z.literal("ok")]) , data: z.string() }),
z.object({ status: z.literal("failed"), error: z.instanceof(Error) }),
]);
myUnion.parse({ status: "success", data: "yippie ki yay" }); The valid type for this would be something like: type myUnion = {
status: "success" | "ok";
data: string;
} | {
status: "failed";
error: Error;
} The workaround is to duplicate the the entry for each value in the inner union. |
Beta Was this translation helpful? Give feedback.
Replies: 5 comments
-
I just ran into this same issue (the case of using a I went here to file an issue and found this was the latest one. Perfect timing! 🤯
I really enjoy using Zod, and many thanks to all who've contributed to make it great, but I feel there could be an improvement made here somewhere... (At least in the documentation? 🥲) |
Beta Was this translation helpful? Give feedback.
-
Thanks for the enum suggestion @conorbrandon. I can't use the enum approach it seems since it only accepts a list of strings and in my actual use case the discriminator is a number. |
Beta Was this translation helpful? Give feedback.
-
Ah, gotcha! |
Beta Was this translation helpful? Give feedback.
-
Is this what you are looking for? const myUnion = z.discriminatedUnion( 'status', [
z.object( {
status: z.literal( 'success' ),
data: z.string(),
} ),
z.object( {
status: z.literal( 'ok' ),
data: z.string(),
} ),
z.object( {
status: z.literal( 'failed' ),
error: z.instanceof( Error ),
} ),
] )
myUnion.parse( { status: 'success', data: 'yippie ki yay' } ) If you found my answer satisfactory, please consider supporting me. Even a small amount is greatly appreciated. Thanks friend! 🙏 |
Beta Was this translation helpful? Give feedback.
-
Hmm, what a shame it only supports |
Beta Was this translation helpful? Give feedback.
Is this what you are looking for?
If you found my answer satisfactory, please consider supporting me. Even a small amount is greatly appreciated. Thanks friend! 🙏
https://github.com/sponsors/JacobWeisenburger