Appetite for xor
method (like joi
) to require one of a set of object keys, but never together
#2797
-
Unless I'm mistaken, a simple helper method for the functionality of The definition of
Instead, all I can find is the recommended use of a chained z.object(...)
.refine(args =>
!(args.val1 !== undefined && args.val2 !== undefined),
{ message: 'val1 and val2 cannot be provided together' },
)
.refine(args =>
args.val1 === undefined && args.val2 === undefined,
{ message: 'one of val1 or val2 must be provided' },
); Is there opposition about introducing such a helper method? I find it very cumbersome to write the refine logic and it's also a bore to read. |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 1 reply
-
I think if you only have a small set of possible combinations of keys, you can use Discriminated Unions |
Beta Was this translation helpful? Give feedback.
-
Does that really fit the case I'm describing?
In my example I reference a rule that refers to The most basic schema representation of this would be:
What is the discriminated union suggestion given there is no common key to check against? This also doesn't feel very scalable.
|
Beta Was this translation helpful? Give feedback.
-
The
So it actually is a XOR functionally. Edit: oh, no. It won't fail when both params are provided. But at least let you have a single P.S.: I actually came here because the |
Beta Was this translation helpful? Give feedback.
-
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 friend! 🙏 |
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 frie…