ts-state-machines
TypeScript icon, indicating that this package has built-in type declarations

1.0.3 • Public • Published

TypeScript State Machines

State machines with type safe transitions

What is this? 🧐

A TypeScript library to create state machines with type safe transitions. The available state transitions for the current state will autocomplete and type check.

This is accomplished by making each state immutable, with each transition method returning the next state.

Examples 🚀

Stoplight

const Stoplight = StateMachine({
  initialState: "red",
  states: {
    red: {
      timer: "green",
    },
    green: {
      timer: "yellow",
    },
    yellow: {
      timer: "red",
    },
  },
} as const);

const stoplight = Stoplight();

// TypeScript will infer this to be 'red';
stoplight.state;

// TypeScript will infer this to be 'green';
stoplight.timer().state;

// TypeScript will infer this to be 'yellow';
stoplight.timer().timer().state;

Promiselike

const Promiselike = StateMachine({
  initialState: "pending",
  states: {
    pending: {
      start: "loading",
    },
    loading: {
      resolve: "resolved",
      reject: "rejected",
    },
    resolved: {},
    rejected: {},
  },
} as const);

const promise = Promiselike();

// TypeScript will infer this to be 'resolved';
promise.start().resolve().state;

// TypeScript will infer this to be 'rejected';
promise.start().reject().state;

Maintaining a reference to the latest state

const Stoplight = StateMachine({
  initialState: "red",
  states: {
    red: {
      timer: "green",
    },
    green: {
      timer: "yellow",
    },
    yellow: {
      timer: "red",
    },
  },
} as const);

let stoplight: StateMachineInstance<typeof Stoplight.config>;

stoplight = Stoplight();
stoplight.state; // 'red'

stoplight = stoplight.timer();
stoplight.state; // 'green'

stoplight = stoplight.timer();
stoplight.state; // 'yellow'

stoplight = stoplight.timer();
stoplight.state; // 'red'

Installation & Usage 📦

  1. Add this package to your project:
    • yarn add ts-state-machines

Highlights

🎁 Zero run time dependencies

🪐 Isomorphic / Universal -- safe to run in any JS context: the browser or on a server

🦶 Small footprint 279 B minified and gzipped

Contributing 👫

PR's and issues welcomed! For more guidance check out CONTRIBUTING.md

Licensing 📃

See the project's MIT License.

Package Sidebar

Install

npm i ts-state-machines

Weekly Downloads

1

Version

1.0.3

License

MIT

Unpacked Size

6.85 kB

Total Files

7

Last publish

Collaborators

  • tatethurston