ts-sum-types
TypeScript icon, indicating that this package has built-in type declarations

0.2.1 • Public • Published

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

Package Sidebar

Install

npm i ts-sum-types

Weekly Downloads

2

Version

0.2.1

License

MIT

Unpacked Size

7.7 kB

Total Files

19

Last publish

Collaborators

  • kinrany