Coder Social home page Coder Social logo

libra-co / ts-xor Goto Github PK

View Code? Open in Web Editor NEW

This project forked from maninak/ts-xor

0.0 0.0 0.0 65 KB

Compose custom types containing mutually exclusive keys, using this generic Typescript helper type.

License: MIT License

Shell 13.60% TypeScript 86.40%

ts-xor's Introduction

ts-xor

Compose custom types containing mutually exclusive keys, using this generic Typescript helper type.

npm version Licence

Downloads per week Downloads per week Repos depending on ts-xor Github stars

Minified and gzipped size 0 Dependencies

Description

Typescript's union operator (|) allows combining two object types A and B, into a superset type C which can contain all the members of both A and B.

But sometimes the requirements dictate that we combine two types with mutually exclusive members. So take the members 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.

The package ts-xor introduces the new custom type XOR. You can use XOR to compose your own custom types with mutually exclusive members.

The XOR type effectively implements the well-known XOR logical operator from boolean algebra as defined by the following truth table:

A B Result Note
0 0 0 achievable with union operator (|) and XOR
0 1 1 achievable with union operator (|) and XOR
1 0 1 achievable with union operator (|) and XOR
1 1 0 achievable only with XOR

Union operator vs the XOR type in practice

If we use the union operator

type A_OR_B = A | B

then the derived type is shown in VS Code like so:

Resulting type when using the union operator

Whereas if we use the XOR mapped type

type A_XOR_B = XOR<A, B>

then the derived type is shown quite differently in VS Code:

Resulting type when using the XOR mapped type

Notice that when using XOR each "variant" of the resulting type contains all keys of one source type plus all keys of the other, with those of the second type defined as optional and at the same time typed as undefined.

This trick will not only forbid defining keys of both source types 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.

Installation

In your typescript powered, npm project, run:

npm install -D ts-xor # yarn add -D ts-xor

Examples

A simple example

// example1.ts

import type { XOR } from 'ts-xor'

interface A {
  a: string
}

interface B {
  b: string
}

let test: XOR<A, B>

test = { a: '' }         // OK
test = { b: '' }         // OK
test = { a: '', b: '' }  // rejected
test = {}                // rejected

A real-life example

Let's assume that we have the following spec for a weather forecast API's response:

  1. A weather forecast object always contains the id and station members
  2. A weather forecast object always contains either a member rain or a member snow, but never both at the same time.
  3. The rain, snow members are objects containing additional forecast accuracy data
  4. The rain, snow members always contain either a member 1h or a member 3h with a number value, but never both keys at the same time.
// example2.ts

import type { XOR } from 'ts-xor'

type ForecastAccuracy = XOR<{ '1h': number }, { '3h': number }>

interface WeatherForecastBase {
  id: number
  station: string
}

interface WeatherForecastWithRain extends WeatherForecastBase {
  rain: ForecastAccuracy
}

interface WeatherForecastWithSnow extends WeatherForecastBase {
  snow: ForecastAccuracy
}

type WeatherForecast = XOR<WeatherForecastWithRain, WeatherForecastWithSnow>

const test: WeatherForecast = {
  id: 1,
  station: 'Acropolis',
  // rain: { '1h': 1 },           // OK
  // rain: { '2h': 1 },           // rejected
  // rain: { '3h': 1 },           // OK
  // rain: {},                    // rejected
  // rain: { '1h': 1 , '3h': 3 }, // rejected
  // lel: { '3h': 1 },            // rejected
  // rain: { '3h': 1, lel: 1 },   // rejected
  // snow: { '3h': 1 },           // OK
                                  // rejected when BOTH `rain` AND `snow` keys are defined at the same time
}

XORing more than two types

If you want to create a type as the product of the logical XOR operation between multiple types (more than two), then nest the generic params.

// example1.ts

import type { XOR } from 'ts-xor'

interface A {
  a: string
}

interface B {
  b: string
}

interface C {
  c: string
}

let test: XOR<A, XOR<B, C>>

test = { a: '' }         // OK
test = { b: '' }         // OK
test = { c: '' }         // OK
test = { a: '', c: '' }  // rejected
test = {}                // rejected

Tests and Coverage

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:

npm run test

NPM

This library is published on NPM.

Licence

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

Contributing

This project's commits comply with the Conventional Commits guidelines.

  1. Fork it (https://github.com/maninak/ts-xor/fork)
  2. Create your feature/fix branch (git checkout -b feat/foobar)
  3. Commit your changes (git commit -am 'feat(foobar): add support for foobar tricks')
  4. Push to the branch (git push origin feat/fooBar)
  5. Create a new Pull Request

ts-xor's People

Contributors

maninak avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.