Compose custom types containing mutually exclusive keys, using this generic Typescript helper type.
Typescript's union operator (
|) allows combining two types
B, into a superset type C which can contain all the members of both
But sometimes the requirements dictate that we combine two types with mutually exclusive members. So take the members
type C = A | B then we want to impose the restriction that we can set either
C.b but never both AND at least one of the two!
Typescript does not support this feature out of the box yet.
This package introduces the new type
XOR. You can use XOR to compose your own custom types with mutually exclusive members.
XOR effectively implements the logical XOR operator from boolean algebra as defined by the following truth table:
In your typescript powered, npm project, run:
npm install -D ts-xor # yarn add -D ts-xor
A simple example
In any typescript file you can just have:
A_XOR_B = // OKA_XOR_B = // OKA_XOR_B = // failsA_XOR_B = // fails
A real-life example
Say that we have the following specification for the response of a weather forecast service:
- A weather forecast object always contains the
- A weather forecast object always contains either a member
rainor a member
snow, but never both at the same time.
- The rain or snow members are objects containing additional forecast accuracy data
- The rain or snow member always contain either a member
1hor a member
3hwith a number value, but never both keys at the same time.
Tests and Coverage
ts-xor is fully covered with acceptance and mutation tests against the typescript compiler itself. The tests can be found inside the
To run all tests locally, execute the following command inside your git-cloned
This library is published on NPM.
Distributed under the MIT license. See
LICENSE.md for more information.
This project's commits comply with the Conventional Commits guidelines.
- Fork it (https://github.com/maninak/ts-xor/fork)
- Create your feature/fix branch (
git checkout -b feat/foobar)
- Commit your changes (
git commit -am 'feat(foobar): add support for foobar tricks')
- Push to the branch (
git push origin feat/fooBar)
- Create a new Pull Request