Gathering detailed insights and metrics for ts-xor
Gathering detailed insights and metrics for ts-xor
Gathering detailed insights and metrics for ts-xor
Gathering detailed insights and metrics for ts-xor
Compose object types containing mutually exclusive keys, using this generic Typescript utility type.
npm install ts-xor
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
106 Stars
87 Commits
5 Forks
1 Watching
3 Branches
1 Contributors
Updated on 22 Oct 2024
Minified
Minified + Gzipped
TypeScript (97.58%)
JavaScript (2.21%)
Shell (0.21%)
Cumulative downloads
Total Downloads
Last day
-6.1%
17,828
Compared to previous day
Last week
10.7%
110,331
Compared to previous week
Last month
19.7%
435,028
Compared to previous month
Last year
25.2%
3,835,575
Compared to previous year
3
The npm package ts-xor
introduces the new mapped type XOR
that helps you compose your own custom TypeScript types containing mutually exclusive object keys.
ts-xor
implements the well-known exclusive or (a.k.a. XOR) logical operator from boolean algebra:
A | B | XOR | union operator (| ) | ts-xor |
---|---|---|---|---|
0 | 0 | 0 | 0 ✅ | 0 ✅ |
0 | 1 | 1 | 1 ✅ | 1 ✅ |
1 | 0 | 1 | 1 ✅ | 1 ✅ |
1 | 1 | 0 | 1 ❌ | 0 ✅ |
|
) enough?Typescript's union operator allows combining two object types A
and B
, into a superset type C which can contain all the keys of both A
and B
.
But sometimes the requirements dictate that we combine two types with mutually exclusive keys.
For example: assume two objects with with keys A.a
and B.b
. Given type C = A | B
then we want to impose the restriction that we can set either C.a
or C.b
but never both AND always at least one of the two!
Typescript does not have this feature built-in.
If we use the union operator
1type A_OR_B = A | B
then the derived type is shown in VS Code like so:
Whereas if we use XOR
:
1type A_XOR_B = XOR<A, B>
then the derived type is shown quite differently in VS Code:
Notice in the example above, that when using XOR
, each union branch of the resulting type contains all keys of one source type plus all keys of the other. At the same time, in each variant, those keys of the other type are defined as optional while additionally they are also typed as undefined.
This trick will not only forbid having keys of both source types defined at the same time (since the type of each key is explicitly undefined
), but also allow us to not need to define all keys all of the time since each set of keys is optional on each variant.
Fun fact: The actual TypeScript code for
XOR
is generated programmatically using the TypeScript Compiler API. 🦾
In your typescript powered, npm project, run:
1npm install -D ts-xor
1import type { XOR } from 'ts-xor' 2 3interface A { a: string } 4interface B { b: string } 5 6let test: XOR<A, B> 7 8test = { a: '' } // OK 9test = { b: '' } // OK 10test = { a: '', b: '' } // error 11test = {} // error
If you want to create a type as the product of the logical XOR operation between multiple types (more than two and even up to 200), then just pass them as additional comma-separated generic params.
1let test: XOR<A, B, C, D, E, F, ...>
ts-xor
can easily handle up to 200 generic params. 💯💯
Using XOR
we can type a function that returns either the data requested from an API or a response object like so:
1type FetchResult<P extends object> = XOR< 2 { data: P }, 3 { error: FetchError<P> }, 4>
Now TypeScript has all the necessary information to infer if FetchResult
contains a data
or an error
key at compile time which results in very clean, yet strictly typed handling code.
Let's assume that we have the following spec for a weather forecast API's response:
id
and station
membersrain
or a member snow
, but never both at the same time.1h
or a member 3h
with a number value, but never both keys at the same time.1type ForecastAccuracy = XOR<{ '1h': number }, { '3h': number }> 2 3interface WeatherForecastBase { 4 id: number 5 station: string 6} 7 8interface WeatherForecastWithRain extends WeatherForecastBase { 9 rain: ForecastAccuracy 10} 11 12interface WeatherForecastWithSnow extends WeatherForecastBase { 13 snow: ForecastAccuracy 14} 15 16type WeatherForecast = XOR<WeatherForecastWithRain, WeatherForecastWithSnow> 17 18const test: WeatherForecast = { 19 id: 1, 20 station: 'Acropolis', 21 // rain: { '1h': 1 }, // OK 22 // rain: { '2h': 1 }, // error 23 // rain: { '3h': 1 }, // OK 24 // rain: {}, // error 25 // rain: { '1h': 1 , '3h': 3 }, // error 26 // lel: { '3h': 1 }, // error 27 // rain: { '3h': 1, lel: 1 }, // error 28 // snow: { '3h': 1 }, // OK 29 // error when BOTH `rain` AND `snow` keys are defined at the same time 30}
The library ts-xor
is fully covered with smoke, acceptance and mutation tests against the typescript compiler itself. The tests can be found inside the test
folder.
To run all tests locally, execute the following command inside your git-cloned ts-xor
folder:
1npm run test
🫶 Follow me on X.
MIT License © 2019-PRESENT Kostis Maninakis
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
4 existing vulnerabilities detected
Details
Reason
Found 0/27 approved changesets -- score normalized to 0
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
Reason
security policy file not detected
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More