Union Types for State Machines
You'll learn how discriminated unions enable compile-time guarantees that your state transitions are valid and complete.
What This Means
A state machine tracks an entity through distinct phases—like a network request going from idle → loading → success or failure. Each state has specific data: loading has no result yet, success has data, and error has an error message.
The problem: If you model this as a single object with optional fields, invalid combinations become possible—like having both data and error defined simultaneously, or marking status as "loading" while data exists.
The solution: Union types let you model each state as a separate, complete type. The type system then ensures only valid states can exist, and forces you to handle every case.
Modeling Valid States with Unions
Think of a state machine like a traffic light: it's red, yellow, or green—never two colors at once, and never "sort of red with a hint of green." Each state is wholly distinct.
type FetchState =
| { status: 'idle' }
| { status: 'loading' }
| { status: 'success'; data: string }
| { status: 'error'; error: string };
Each union member documents one valid state. The status discriminant lets TypeScript narrow the type:
function handleState(state: FetchState) {
switch (state.status) {
case 'idle':
// state is { status: 'idle' }
console.log('Not started');
break;
case 'loading':
// state is { status: 'loading' }
console.log('Fetching...');
break;
case 'success':
// state is { status: 'success'; data: string }
console.log(state.data.toUpperCase());
break;
case 'error':
// state is { status: 'error'; error: string }
console.log(state.error);
break;
}
}
You can't accidentally access data when in the error state—TypeScript won't compile. You can't forget to handle the loading state—exhaustiveness checking catches it.
This pattern documents all possible states at the type level, prevents impossible combinations, and guides refactoring when states evolve.
Key Takeaway: Union types turn state machines into self-documenting, compiler-verified contracts where every state is explicit and every transition is type-safe.