Generic State Machines
What you'll learn: How to use generics to create type-safe state machines that only allow valid transitions between states.
The Problem with Untyped State Machines
A state machine controls transitions between specific states based on events. For example, a traffic light moves from green → yellow → red → green. Without types, you could accidentally transition from green directly to red, or send invalid events.
Parameterizing States and Events
Generic state machines use type parameters to define:
- Which states exist (as a union type)
- Which events can trigger transitions (as a union type)
- Which transitions are valid (enforced through discriminated unions)
type State = 'idle' | 'loading' | 'success' | 'error';
type Event =
| { type: 'FETCH' }
| { type: 'SUCCESS'; data: string }
| { type: 'FAILURE'; error: string }
| { type: 'RESET' };
interface Machine<S, E> {
state: S;
transition: (event: E) => S;
}
Here, Machine<S, E> is generic over state type S and event type E.
Enforcing Valid Transitions
You can constrain transitions by mapping each state to its allowed events:
type Transition<S extends State> =
S extends 'idle' ? { type: 'FETCH' } :
S extends 'loading' ? { type: 'SUCCESS'; data: string } | { type: 'FAILURE'; error: string } :
{ type: 'RESET' };
Now TypeScript knows that from idle, only FETCH is valid—not SUCCESS or FAILURE.
Real-World Analogy
Think of a vending machine: you can't "dispense item" before "payment received." Generics encode those rules, so the compiler prevents impossible sequences.
Key Takeaway: Generic state machines parameterize states and events, allowing TypeScript to enforce valid state flows at compile time, preventing illegal transitions.