union-exclusive
TypeScript icon, indicating that this package has built-in type declarations

0.0.3 • Public • Published

union-exclusive

NPM version NPM yearly download

Compose custom types containing multiple mutually exclusive type and works with Primitive and Tuple.

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

type MyUnionType = Union<
  A | B | C | string | number[] | [string, number, boolean]
>;

Union type take a list of type without size restriction include Primitive and Tuple type. Check the examples for more comprehension

The implementation

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

yarn add -D union-exclusive

Examples

Codesandbox: https://codesandbox.io/s/union-exclusive-demo-7flig

import {Union} from 'union-exclusive';

interface Person1 {
  name: string;
}

interface Person2 {
  age: number;
}

interface Person3 {
  rich: boolean;
}

type Person = Union<Person1 | Person2 | Person3>;

const person_1: Person = {
  name: 'john doe',
}; // OK

const person_2: Person = {
  age: 18,
}; // OK

const person_3: Person = {
  rich: false,
}; // OK

const person_4: Person = {
  name: 'john doe',
  age: 18,
}; // FAILS

const person_5: Person = {
  age: 18,
  rich: false,
}; // FAILS

const person_6: Person = {
  name: 'john doe',
  rich: false,
}; // FAILS

// And
// Works with Primitive and Tuple
type AnotherPerson = Union<
  Person1 | Person2 | Person3 | boolean | boolean[] | [string, number, boolean]
>;
const person_7: AnotherPerson = true;
const person_8: AnotherPerson = [true, true];
const person_9: AnotherPerson = ['john doe', 18, true];

Related

License

MIT

Dependents (0)

Package Sidebar

Install

npm i union-exclusive

Weekly Downloads

3

Version

0.0.3

License

MIT

Unpacked Size

4.61 kB

Total Files

5

Last publish

Collaborators

  • nghiepit