0Pricing
TypeScript Academy · Lesson

Modeling State Machines

Represent finite states with discriminated unions.

States as a Discriminated Union

UI and async flows have distinct states: idle, loading, success, error. Modeling them as a discriminated union makes each state carry exactly the data it needs.

type State =
  | { status: "idle" }
  | { status: "loading" }
  | { status: "success"; data: string }
  | { status: "error"; message: string };

const s: State = { status: "idle" };
console.log(s.status);

Payload Per State

Only the success state has data; only error has a message. Idle and loading carry nothing extra, which prevents stale data leaking between states.

type State =
  | { status: "idle" }
  | { status: "loading" }
  | { status: "success"; data: number[] }
  | { status: "error"; message: string };

const ok: State = { status: "success", data: [1, 2, 3] };
console.log(ok.status, "data" in ok ? ok.data : null);

All lessons in this course

  1. Building Discriminated Unions
  2. Narrowing on the Discriminant
  3. Exhaustiveness Checking with never
  4. Modeling State Machines
← Back to TypeScript Academy