Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/hojberg/sums-up

SumTypes in TypeScript
https://github.com/hojberg/sums-up

adt fp functional-programming javascript typescript

Last synced: 3 months ago
JSON representation

SumTypes in TypeScript

Awesome Lists containing this project

README

        

👍 Sums Up
===

### Installation

```
npm install sums-up
```

### Example

In TypeScript:

```typescript
import SumType from 'sums-up';

class Maybe extends SumType<{ Just: [T]; Nothing: [] }> {}

function Just(value: T): Maybe {
return new Maybe("Just", value);
}

function Nothing(): Maybe {
return new Maybe("Nothing");
}

const x = Just("foo");

const result = x.caseOf({
Nothing: () => "nope",
Just: (a) => a + "bar",
});
```

Or in JavaScript

```javascript
import SumType from 'sums-up';

class Maybe extends SumType {}

function Just(value) {
return new Maybe("Just", value);
}

function Nothing() {
return new Maybe("Nothing");
}

const x = Just("foo");

const result = x.caseOf({
Nothing: () => "nope",
Just: (a) => a + "bar",
});
```

### Wildcard Matching

If the kind of a sum type instance isn't present in the pattern given to `caseOf`, a default key called `_` will be used instead.

```ts
import SumType from 'sums-up';

class RequestState extends SumType<{
NotStarted: [];
Connecting: [];
Downloading: [number];
Completed: [T];
Failed: [string];
}> {}

const state = new RequestState('Failed', 'Connection reset.');
const progressPercentage = state.caseOf({
Downloading: pct => pct,
Completed: () => 100,
_: () => 0
});
```

Contributors:

@hojberg @dfreeman @AdamEdgett