Exclusive Or and the Optional never Trick
Exclusive Or and the Optional never Trick
Effective TypeScript: Exclusive Or and the Optional never Trick
Thanks Dan for this blog ! :) what about type XOR<A, B> = Exclude<A | B, A & B>
That's a cute idea (and mathematically correct!) but unfortunately TypeScript isn't able to follow along:
type XOR<A, B> = Exclude<A | B, A & B>
type ExclusiveThing = XOR<ThingOne, ThingTwo>;
// ^? type ExclusiveThing = ThingOne | ThingTwo
The issue is that the Exclude generic filters unions; it won't break up a "base" type like an interface or a string.
Hey @danvk! Thank you for mentioning ts-essentials.
This type hasn't been added to TypeScript since 2017, you can read more in https://github.com/microsoft/TypeScript/issues/14094
The utility type existed in ts-essentials for a long time but it didn't have a support of variadic XOR which last year was implemented in ts-xor - https://github.com/microsoft/TypeScript/issues/14094#issuecomment-1695887662 (It's also supported in ts-essentials@10)