Course contentsShow
← TypeScript
Lesson 410 of 1,7969. Union TypesFree lesson

Discriminated Unions for State Machines

Modeling finite state machines where each state is a variant with state-specific data.

Discriminated Unions for State Machines

What you'll learn: How to use discriminated unions to model finite state machines where each state carries its own unique data.


The State Machine Problem

A state machine has distinct states, and each state often needs different data. Think of a network request: it starts "idle" (no data), becomes "loading" (maybe with a cancel token), then either "success" (with response data) or "error" (with an error message). Each state has its own shape.


Modeling States as a Discriminated Union

Instead of a single object with optional properties everywhere, use a discriminated union where each state is a separate type:

type RequestState =
  | { status: 'idle' }
  | { status: 'loading'; startedAt: number }
  | { status: 'success'; data: string }
  | { status: 'error'; message: string };

Here status is the discriminant property. Each variant represents one state with state-specific data.


Using the State Machine

When you narrow by status, TypeScript knows exactly which properties are available:

function handleRequest(state: RequestState) {
  switch (state.status) {
    case 'idle':
      console.log('Not started yet');
      break;
    case 'loading':
      console.log(`Loading since ${state.startedAt}`);
      break;
    case 'success':
      console.log(`Data: ${state.data}`);
      break;
    case 'error':
      console.log(`Error: ${state.message}`);
      break;
  }
}

This pattern prevents impossible states (like having both data and message) and ensures you handle every state.


Key Takeaway: Discriminated unions let you model state machines where each state is a distinct variant with state-specific data, giving you compile-time guarantees that you handle all states correctly and access only valid properties.