https://github.com/hojberg/sums-up
SumTypes in TypeScript
https://github.com/hojberg/sums-up
adt fp functional-programming javascript typescript
Last synced: 16 days ago
JSON representation
SumTypes in TypeScript
- Host: GitHub
- URL: https://github.com/hojberg/sums-up
- Owner: hojberg
- Created: 2018-09-03T21:26:37.000Z (over 7 years ago)
- Default Branch: main
- Last Pushed: 2023-01-05T10:13:59.000Z (about 3 years ago)
- Last Synced: 2025-04-14T01:35:57.452Z (11 months ago)
- Topics: adt, fp, functional-programming, javascript, typescript
- Language: TypeScript
- Size: 951 KB
- Stars: 30
- Watchers: 2
- Forks: 2
- Open Issues: 10
-
Metadata Files:
- Readme: README.md
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