JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 22
  • Score
    100M100P100Q48167F
  • License MIT

Delightful Sum Types in TypeScript

Package Exports

  • itsamatch
  • itsamatch/lib/index.js

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (itsamatch) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

NPM Package Build Size

It's a match!

Itsamatch is a tiny set of types and utilities to define and use variants / tagged unions / sum types in a more declarative way in TypeScript.

Usage

itsamatch exposes three functions (match, matchMany, genConstructors) and a few types that make it easier to construct data types. Below is a simple example showing how it can be used to create a linked list data type :

import { DataType, genConstructors, match } from 'itsamatch';

// a list is a data type with two variants:
type List<T> = DataType<{
    Nil: {},
    Cons: { head: T, tail: List<T> }
}>;

// generate default variant constructors for lists of numbers
const { Nil, Cons } = genConstructors<List<number>>(['Nil', 'Cons']);

// use the match function to compute the length of a list
const len = <T>(list: List<T>): number => match(list, {
    Nil: () => 0,
    Cons: ({ tail }) => 1 + len(tail)
});

const same = <T>(a: List<T>, b: List<T>): boolean => matchMany([a, b], {
  'Nil Nil': () => true,
  'Cons Cons': (l, r) => l.head === r.head && same(l.tail, r.tail),
  _: () => false,
});

const size = len(Cons({ head: 1, tail: Cons({ head: 2, tail: Nil() }) })); // 2
const sameElems = same(Cons({ head: 1, tail: Nil() }), Nil()); // false

More examples are available in the /examples folder