Skip to content
This repository has been archived by the owner on Jun 16, 2019. It is now read-only.
/ ts-sum-types Public archive

Algebraic sum types for TypeScript, designed after Rust's enums

License

Notifications You must be signed in to change notification settings

Kinrany/ts-sum-types

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

19 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

ts-sum-types

Overview

Algebraic sum types (aka tagged unions) for TypeScript.

Designed after Rust's enums.

Installation

npm install --save ts-sum-types

This library exports a ES6 module with types.

import { create_enum_namespace, type, EnumUnion} from 'ts-sum-types';

// Create an `enum` to classify a web event.
const WebEvent = create_enum_namespace({
  // An `enum` may either be `unit-like`,
  PageLoad: type(),
  PageUnload: type(),
  // like tuple structs,
  KeyPress: type<number>(),
  Paste: type<string>(),
  // or like structures.
  Click: type<{ x: number; y: number }>(),
});
type WebEvent = EnumUnion<typeof WebEvent>;

// A function which takes a `WebEvent` enum as an argument
function inspect(event: WebEvent) {
  event.match({
    PageLoad: () => console.log("page loaded"),
    PageUnload: () => console.log("page unloaded"),
    // Destructure `c` from inside the `enum`.
    KeyPress: (c) => console.log(`pressed '${c}'.`),
    Paste: (s) => console.log(`pasted "${s}".`),
    // Destructure `Click` into `x` and `y`.
    Click({ x, y }) {
      console.log(`clicked at x=${x}, y=${y}.`);
    },
  });
}

Development

npm install
npm run build
npm publish

Prior art

About

Algebraic sum types for TypeScript, designed after Rust's enums

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published