Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/nathsou/itsamatch
Delightful Sum Types in TypeScript
https://github.com/nathsou/itsamatch
Last synced: about 2 months ago
JSON representation
Delightful Sum Types in TypeScript
- Host: GitHub
- URL: https://github.com/nathsou/itsamatch
- Owner: nathsou
- Created: 2021-04-05T19:48:54.000Z (over 3 years ago)
- Default Branch: main
- Last Pushed: 2024-01-15T01:46:58.000Z (12 months ago)
- Last Synced: 2024-11-10T23:04:44.886Z (about 2 months ago)
- Language: TypeScript
- Size: 25.4 KB
- Stars: 1
- Watchers: 2
- Forks: 1
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
[![NPM Package][npm]][npm-url]
[![Build Size][build-size]][build-size-url]# 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](https://en.wikipedia.org/wiki/Cons#Lists) :```typescript
import { DataType, constructors, match } from 'itsamatch';// a list is a data type with two variants:
type List = DataType<{
Nil: {},
Cons: { head: T, tail: List }
}>;// generate default variant constructors for lists of numbers
const { Nil, Cons } = constructors>().get('Nil', 'Cons');// use the match function to compute the length of a list
const len = (list: List): number => match(list, {
Nil: () => 0,
Cons: ({ tail }) => 1 + len(tail)
});const same = (a: List, b: List): 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
[npm]: https://img.shields.io/npm/v/itsamatch
[npm-url]: https://www.npmjs.com/package/itsamatch
[build-size]: https://badgen.net/bundlephobia/minzip/itsamatch
[build-size-url]: https://bundlephobia.com/result?p=itsamatch