Skip to content

cannot figure out how to create a schema from the discriminator key of a discriminated union #3032

Answered by JacobWeisenburger
laser asked this question in Q&A
Discussion options

You must be logged in to vote

Is this what you are looking for?

const ResultStatusSchema = z.enum( [ 'success', 'failed' ] )
type ResultStatusType = z.infer<typeof ResultStatusSchema>
// type ResultStatusType = 'success' | 'failed'

const ResultSchema = z.discriminatedUnion( 'status', [
    z.object( { status: ResultStatusSchema.extract( [ 'success' ] ), data: z.string() } ),
    z.object( { status: ResultStatusSchema.extract( [ 'failed' ] ), error: z.instanceof( Error ) } ),
] )
type ResultType = z.infer<typeof ResultSchema>
// type ResultType = {
//     status: 'success'
//     data: string
// } | {
//     status: 'failed'
//     error: Error
// }

If you found my answer satisfactory, please consider supporting me. E…

Replies: 4 comments 12 replies

Comment options

You must be logged in to vote
2 replies
@laser
Comment options

@laser
Comment options

Comment options

You must be logged in to vote
2 replies
@Panth977
Comment options

@laser
Comment options

Comment options

You must be logged in to vote
5 replies
@laser
Comment options

@JacobWeisenburger
Comment options

@laser
Comment options

@JacobWeisenburger
Comment options

@Panth977
Comment options

Answer selected by laser
Comment options

You must be logged in to vote
3 replies
@tommysullivan
Comment options

@tommysullivan
Comment options

@tommysullivan
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
5 participants
Converted from issue

This discussion was converted from issue #3030 on December 09, 2023 15:30.