Skip to content

Appetite for xor method (like joi) to require one of a set of object keys, but never together #2797

Discussion options

You must be logged in to vote

Is this what you are looking for?

const schema = z.union( [
    z.object( { val1: z.string() } ).strict(),
    z.object( { val2: z.string() } ).strict(),
] )

console.log( schema.parse( { val1: 'a' } ) ) // { val1: 'a' }
console.log( schema.parse( { val2: 'b' } ) ) // { val2: 'b' }

const result = schema.safeParse( { val1: 'a', val2: 'b' } )
!result.success && console.log( result.error.issues )
// [
//     {
//         code: "unrecognized_keys",
//         keys: [ "val2" ],
//         path: [],
//         message: "Unrecognized key(s) in object: 'val2'"
//     }
// ]

If you found my answer satisfactory, please consider supporting me. Even a small amount is greatly appreciated. Thanks frie…

Replies: 4 comments 1 reply

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
1 reply
@Lonli-Lokli
Comment options

Answer selected by JacobWeisenburger
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 #2685 on September 25, 2023 13:50.