~/alexsh.blog

$ cat advanced-typescript/16-type-safe-state-machines.md

Type-Safe State Machines

February 9, 20261 min readpart 16/20

Difficulty: Advanced. Prerequisites: Discriminated unions, mapped types, conditional types, generics.

Type-safe state machines use TypeScript's type system to enforce valid state transitions at compile time. Only valid events for the current state are allowed, and the resulting state type is correctly inferred.

Key concepts

  • Defining states as discriminated unions
  • Mapping valid events/transitions for each state
  • Restricting event handlers to valid events for current state
  • Inferring the next state type from transitions

Example

codets
type State =
  | { s: 'idle' }
  | { s: 'loading'; t: number }
  | { s: 'done'; data: string };

type Event =
  | { e: 'FETCH' }
  | { e: 'DONE'; data: string }
  | { e: 'RESET' };

type Valid = { idle: 'FETCH'; loading: 'DONE'; done: 'RESET' | 'FETCH' };

type Allowed<S extends State> = Extract<Event, { e: Valid[S['s']] }>;

// Infer the next state from a transition
type NextState = { idle: { s: 'loading'; t: number }; loading: { s: 'done'; data: string }; done: { s: 'idle' } | { s: 'loading'; t: number } };

function transition<S extends State>(state: S, event: Allowed<S>): NextState[S['s']] {
  switch (state.s) {
    case 'idle': return { s: 'loading', t: Date.now() };
    case 'loading': {
      const ev = event as Extract<Event, { e: 'DONE' }>; // narrowed by Allowed
      return { s: 'done', data: ev.data };
    }
    case 'done': return event.e === 'RESET'
      ? { s: 'idle' } : { s: 'loading', t: Date.now() };
  }
}

const idle: State = { s: 'idle' };
transition(idle, { e: 'FETCH' }); // OK — returns { s: 'loading'; t: number }
// transition(idle, { e: 'DONE', data: '' }); // Error!

// Real-world: XState v5 — setup({ types: { events: {} as Event } }).createMachine(...)

Resources

Practice

Hints

  • Define a mapping type that maps each state to its valid events.
  • Use Extract<Event, { e: ValidEvents }> to restrict which events are allowed for a given state.