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 - Add this package to your project:
yarn add ts-state-machines
Highlights
👫
Contributing PR's and issues welcomed! For more guidance check out CONTRIBUTING.md
📃
Licensing See the project's MIT License.