Skip to content

Using a union for the discriminator with discriminatedUnions fails #2776

Discussion options

You must be logged in to vote

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! 🙏
https://github.com/sponsors/JacobWeisenburger

Replies: 5 comments

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Answer selected by JacobWeisenburger
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
4 participants
Converted from issue

This discussion was converted from issue #2637 on September 23, 2023 15:21.