Skip to content
Tutorials Center
My learning

Topics

Lesson 80 of 96 ยท Projects

Project: State Machine

Build state machines in TypeScript - a traffic light with a checked transition table, a generic machine with const type parameters, and an order workflow.

A lot of bugs are really state bugs: an order shipped before it was paid, a button that can be clicked twice while a request is in flight, a door that opens while it's locked. They happen when the rules about "what can happen next" are spread across if statements all over the code. A state machine puts those rules in one place: a finite set of states, a set of events, and a table saying which event moves which state to which other state. Everything else is forbidden.

TypeScript is very good at state machines, because the rules can be checked at compile time. In this project you'll build three of them, each stricter than the last: a traffic light whose transition table the compiler checks for typos and missing states, a reusable createMachine function that infers states and events from a config object, and an order workflow where each state carries its own data and each state accepts only certain events. Every stage is a complete program you can run.

The plan

Stage What you build Main TypeScript ideas
1 A traffic light with a transition table Literal unions, mapped types, Record
2 A generic createMachine and a running service const type parameters, NoInfer, infer
3 An order workflow whose states carry data Discriminated unions, correlated unions, a handler per state
4 Allowed events per state, guards, history and replay as const + satisfies, Extract, never, reducers

Stage 1: a traffic light

A traffic light (the European kind, with a red-and-amber phase) has five states and three events. States and events are unions of string literals, and the transition table is a mapped type: for every state, an object that may map each event to a next state.

TypeScript
type TransitionTable = {
  readonly [S in LightState]: { readonly [E in LightEvent]?: LightState };
};

That one type gives three compile-time guarantees: every state has an entry, every event name is real, and every target is a real state.

TypeScript Stage 1: a traffic light with a checked table

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The light runs through a full cycle, a fault switches it to flashing amber, the next TIMER is ignored (flashing has no TIMER transition), and REPAIR brings it back to red. Notice what isn't in the code: there's no if (state === 'green' && event === 'TIMER') chain. The table is the logic.

The Record<LightState, โ€ฆ> tables for lamps and durations make the same promise as the transition table: one entry per state. Add a sixth state to LightState and every one of the three tables stops compiling until it handles it. To see how strict the table is, here's one with two mistakes. It fails on purpose:

TypeScript A broken transition table (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The compiler reports the typo first, and even suggests the fix:

TEXT
main.ts(10,15): error TS2820: Type '"gren"' is not assignable to type 'LightState | undefined'. Did you mean '"green"'?

(The | undefined is there because each event entry is optional.) Fix the typo and run again, and the second mistake appears. TypeScript checks the properties inside an object literal before it checks for missing ones, so one error can hide another until it's fixed:

TEXT
main.ts(8,7): error TS2741: Property 'flashing' is missing in type '{ red: { TIMER: "redAmber"; FAULT: "flashing"; }; redAmber: { TIMER: "green"; FAULT: "flashing"; }; green: { TIMER: "amber"; FAULT: "flashing"; }; amber: { TIMER: "red"; FAULT: "flashing"; }; }' but required in type 'TransitionTable'.

The typo would have sent the light into a state that doesn't exist, and the missing flashing state would have meant a light that can never recover from a fault. Both are caught before the program runs.

Stage 2: a generic createMachine

Writing LightState and LightEvent by hand and then repeating every name in the table works, but it's duplication. Libraries such as XState go the other way: you write only the config object and the types are inferred from it. You can build the same thing in a few lines with two modern features from Generic Constraints and Defaults:

  • const type parameters (TypeScript 5.0): <const S extends string> makes TypeScript infer the literal names 'closed' | 'opened' | 'locked' instead of widening them to string.
  • NoInfer<S> (TypeScript 5.4): the initial state and the transition targets must be states, but they must not add states to the inferred union. Wrapping them in NoInfer tells TypeScript to infer S only from the keys of states and merely check the other positions.
TypeScript
interface MachineConfig<S extends string, E extends string> {
  readonly initial: NoInfer<S>;
  readonly states: { readonly [K in S]: { readonly on?: { readonly [Ev in E]?: NoInfer<S> } } };
}

Without NoInfer, a typo like OPEN: 'opend' would be inferred as a new state named opend. With it, the typo is reported for what it is.

The machine itself is pure data plus two functions. A separate Service class runs a machine: it holds the current state, accepts events with send and notifies subscribers.

TypeScript Stage 2: createMachine with inferred states and events

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The door rejects LOCK while open and OPEN while locked, and each rejection lists the events that are possible, computed from the same config. The @ts-expect-error line confirms that KICK is not a DoorEvent; the call never compiles without the directive. (With the directive, the line does run, and send returns false because the config has no KICK transition.)

StateOf and EventOf use infer in a conditional type to pull the unions back out of a machine, so the rest of the program can name them without repeating the strings.

Try changing UNLOCK: 'closed' to UNLOCK: 'clsoed'. The compiler reports error TS2820 at the typo, with "Did you mean '"closed"'?". Then replace NoInfer<S> in the targets with plain S and try again. Now 'clsoed' is inferred as a fourth state, and the error moves: TS2741 complains that states has no clsoed entry, pointing at the whole config instead of the typo. NoInfer keeps the inferred union honest and the error message where the mistake is.

Stage 3: states that carry data

The door's states are just names. A real order workflow needs data that depends on the state: a cart has items; a placed order also has an order id; a paid order also has a payment id; a shipped order has a tracking number; a cancelled order has a reason. Modelling that as one object with optional fields would allow "shipped but not paid" again. Instead, each state is its own member of a discriminated union.

The trick in this stage is how the union is built. We start from a plain map of state names to their data, and derive the union from it:

TypeScript
interface StateData {
  cart: { items: readonly Item[] };
  placed: { orderId: string; items: readonly Item[] };
  // ...
}
type StateOf<S extends Status> = { readonly status: S } & Readonly<StateData[S]>;
type OrderState = { [S in Status]: StateOf<S> }[Status]; // the union of all states

The same map produces a Handlers type with one function per state, each receiving exactly that state's type. Forget a state and the handlers object doesn't compile. And because both types come from the same map, TypeScript can check the dispatch call handlers[state.status](state, event): it understands that the handler and the state belong together. This pattern is called a correlated union, and it avoids the assertion you'd otherwise need there.

TypeScript Stage 3: an order workflow with typed states

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The output shows the workflow enforcing its rules: placing an empty cart is rejected, paying before placing is rejected, and cancelling a shipped order is rejected. Look at describe: inside each case, TypeScript knows exactly which fields exist, so state.trackingNumber is only reachable for shipped and delivered orders. The function has no default branch, yet it compiles with an explicit string return type, because TypeScript can see that the six cases are exhaustive.

Each handler also builds states, and those object literals are checked against OrderState. A handler that tried to create a shipped order without a tracking number, or a handlers object that forgot a state, would not compile. This shortened version shows both mistakes and fails on purpose:

TypeScript Forgetting a handler or a field (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The compiler first reports error TS2322 at line 15: the returned object matches no member of OrderState. The message is four lines long, and as usual with nested types, the last line names the actual cause: Property 'trackingNumber' is missing in type '{ status: "shipped"; orderId: string; }' but required in type 'Readonly<{ orderId: string; trackingNumber: string; }>'. A shipped order without a tracking number can't be built.

Add trackingNumber: 'T1' to that object and run again. Now the second mistake surfaces at line 14: error TS2741: Property 'delivered' is missing in type โ€ฆ but required in type 'Handlers'. The workflow can't compile until every state has a handler.

Stage 4: allowed events, guards, history and replay

Stage 3 rejects invalid events with a bare undefined. Users deserve a reason, and a UI needs to know which buttons to enable. This final stage adds:

  1. A table of allowed events per state, written once with as const and checked with satisfies. Each handler then receives only the events its state allows, as Extract<OrderEvent, { type: โ€ฆ }>, so its switch is exhaustive without a default, and the final states' handlers receive never.
  2. Guards with reasons. Handlers return either a new state or a string explaining the refusal (for example "the cart is empty").
  3. A history of every transition and replay: because transitions are pure functions, the current state can be rebuilt from the list of events at any time, the core idea behind event sourcing.
TypeScript Stage 4: the complete order workflow

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The output is a complete audit trail: every rejected event comes with a reason (not allowed in this state, a zero quantity, an empty cart, a wrong payment amount, and finally anything at all after cancellation), and the history lists only the accepted transitions. Replaying the accepted events from an empty cart produces exactly the same final state, which is how event-sourced systems rebuild state after a restart.

The types do a lot of quiet work here:

  • as const satisfies โ€ฆ keeps the literal arrays (readonly ['PAY', 'CANCEL']) while checking that every state is listed and every entry is a real event type. A plain annotation would widen the arrays and lose that information.
  • AllowedEvent<'placed'> is Extract<OrderEvent, { type: 'PAY' | 'CANCEL' }>, so the placed handler's switch covers exactly two cases and needs no default. Add 'SHIP' to allowed.placed and the handler stops compiling until it handles shipping, because it would otherwise return undefined, which isn't an OrderState | string.
  • Final states get never. AllowedEvent<'delivered'> extracts nothing, so event is never and assertNever(event) documents (and proves) that the handler can't be reached.
  • isAllowed is a type predicate (event is AllowedEvent<S>), so after the check in step the call handlers[state.status](state, event) type-checks as a correlated call, with no assertion.
  • Pure transitions (step doesn't modify anything) make history, replay and testing trivial: you can test any transition by calling step with a state and an event.

For large applications, libraries such as XState add hierarchical and parallel states, delayed transitions, side effects ("actions") and visual editors on top of the same ideas, with types inferred from the config like stage 2. Building a small machine yourself, as here, makes those libraries much easier to understand.

Ideas for extending the machines

  • Add an onEnter map ({ [S in Status]?: (state: StateOf<S>) => void }) and call the right hook after each transition, for example to send emails.
  • Add a RETURN event from delivered to a new returned state, and watch the compiler list every table and handler you must update.
  • Give the traffic light real timing with setTimeout, and a using-based disposable service that stops its timer automatically.
  • Generate a Mermaid diagram (stateDiagram-v2) from the allowed table or the stage 2 config.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. The transition table is typed { [S in LightState]: { [E in LightEvent]?: LightState } }. What happens if you leave out the entry for one state?

    The mapped type requires one property per state, so a missing state is error TS2741. Only the inner event entries are optional.
  2. 2. In createMachine<const S extends string, const E extends string>, why are the targets typed NoInfer<S>?

    Without NoInfer, target strings also contribute to S, so a typo like 'clsoed' would be added to the state union. NoInfer makes those positions checks only.
  3. 3. What does type OrderState = { [S in Status]: StateOf<S> }[Status] produce?

    The mapped type builds an object of state types keyed by status, and indexing it with [Status] turns that object into the union of its property types.
  4. 4. In stage 4, what is the type of event in the delivered handler?

    allowed.delivered is an empty tuple, so its element type is never and Extract<OrderEvent, { type: never }> is never. The handler can never be called with a real event.
  5. 5. Why can Order.replay rebuild the final state from the accepted events?

    step never mutates anything and depends only on its inputs, so reducing over the same events always produces the same state.

Summary

  • A state machine lists states, events and allowed transitions in one place; everything not listed is forbidden.
  • A mapped transition table ({ [S in State]: { [E in Event]?: State } }) makes the compiler check for missing states, unknown events and misspelled targets.
  • const type parameters infer literal state and event names from a config; NoInfer keeps transition targets from inventing new states; infer extracts the unions again.
  • Build state unions from a StateData map: the same map gives you one typed handler per state and a correlated dispatch without assertions.
  • as const satisfies keeps an allowed-events table both literal and checked; Extract gives each handler only its allowed events, and final states get never.
  • Pure transition functions make history, replay and tests simple.

Next: Project: Typed API Client