effective-typescript icon indicating copy to clipboard operation
effective-typescript copied to clipboard

Exclusive Or and the Optional never Trick

Open utterances-bot opened this issue 2 years ago • 3 comments

Exclusive Or and the Optional never Trick

Effective TypeScript: Exclusive Or and the Optional never Trick

https://effectivetypescript.com/2021/11/11/optional-never/

utterances-bot avatar Mar 19 '22 21:03 utterances-bot

Thanks Dan for this blog ! :) what about type XOR<A, B> = Exclude<A | B, A & B>

aleclofabbro avatar Mar 19 '22 21:03 aleclofabbro

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.

danvk avatar Mar 20 '22 15:03 danvk

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)

Beraliv avatar Apr 27 '24 19:04 Beraliv