ts-xors

1.0.3 • Public • Published

ts-xors

Compose custom types containing multiple mutually exclusive type.

npm version

Description

The problem

Using mutually exclusives types (XOR) is not a default feature in Typescript, see this

The solution

This package allow it by introducing the new type XORS type

let usage: XORS<[A, B, C, ...]>

XORS type take an array of type without size restriction. Check the examples for more comprehension

The implementation

There is multiple way of achieving the same result, be for this specific problem we're using the work of tjjfvi. As he show in this Stackoverflow

We are ending up with this truth table.

A B C ... Result
0 0 0 ... 0
1 0 0 ... 1
0 1 0 ... 1
0 0 1 ... 1
1 1 0 ... 0
1 0 1 ... 0
0 1 1 ... 0
1 1 1 ... 0

Installation

In your typescript project, run:

npm install -D ts-xors
# or
yarn add -D ts-xors

Examples

1 - Default Case

import XORS from "ts-xors"

interface A {
  a: string
}
interface B {
  b: string
}
interface C {
  c: string
}

let defaultExample: XORS<[A, B, C]>

defaultExample = {} // FAILS
defaultExample = {a: ""} // WORK
defaultExample = {b: ""} // WORK
defaultExample = {c: ""} // WORK
defaultExample = {a: "", b: ""} // FAILS
defaultExample = {b: "", c: ""} // FAILS
...

2 - Simple Case

import XORS from "ts-xors";

interface A {
  a: string;
}
interface B {
  b: string;
}

let simpleExample: XORS<[A, B]>;
simpleExample = {}; // FAILS
simpleExample = { a: "" }; // WORK
simpleExample = { b: "" }; // WORK
simpleExample = { a: "", b: "" }; // FAILS

Licence

Distributed under the MIT license. See LICENSE.md for more information.

Links

This library is published on NPM. Check me on Twitter

Package Sidebar

Install

npm i ts-xors

Weekly Downloads

1

Version

1.0.3

License

MIT

Unpacked Size

4.84 kB

Total Files

6

Last publish

Collaborators

  • timeo1210