~/alexsh.blog

$ cat advanced-typescript/01-discriminated-unions-and-exhaustiveness.md

Discriminated Unions and Exhaustiveness

February 9, 20261 min readpart 01/20

Difficulty: Upper Intermediate. Prerequisites: Union types, type narrowing, never type.

Discriminated unions (tagged unions) use a common property to distinguish between variants, enabling TypeScript to narrow types in control flow. This is the foundation for modeling domain logic, API responses, Redux-style actions, and state machines. Master this first — it’s used throughout advanced TypeScript patterns.

Key concepts

  • Single and multiple discriminant properties
  • Exhaustiveness checking with the never type
  • Extracting and manipulating union variants
  • Narrowing with in operator, typeof, and instanceof
  • Nested discriminated unions for complex state
  • Generic discriminated union factories

Example

codets
// Basic discriminated union
type Result<T, E = Error> =
  | { ok: true; value: T }
  | { ok: false; error: E };

function handleResult<T>(result: Result<T>) {
  if (result.ok) {
    console.log(result.value);  // TS knows value exists
  } else {
    console.error(result.error); // TS knows error exists
  }
}

// EXHAUSTIVENESS CHECKING with never
type Action =
  | { type: 'INCREMENT'; amount: number }
  | { type: 'DECREMENT'; amount: number }
  | { type: 'RESET' };

function assertNever(x: never): never {
  throw new Error(`Unexpected: ${JSON.stringify(x)}`);
}

function reducer(state: number, action: Action): number {
  switch (action.type) {
    case 'INCREMENT': return state + action.amount;
    case 'DECREMENT': return state - action.amount;
    case 'RESET': return 0;
    default: return assertNever(action); // Error if case missing!
  }
}

// EXTRACT UNION VARIANTS
type ExtractVariant<U, T> = U extends { type: T } ? U : never;
type IncrementAction = ExtractVariant<Action, 'INCREMENT'>;

// NARROWING with 'in' operator
type Fish = { swim(): void };
type Bird = { fly(): void };
function move(a: Fish | Bird) {
  if ('swim' in a) a.swim(); // narrowed to Fish
  else a.fly();              // narrowed to Bird
}

// NESTED DISCRIMINATED UNION
type APIResult =
  | { status: 'success'; data: { kind: 'user'; name: string } | { kind: 'post'; title: string } }
  | { status: 'error'; message: string };

// GENERATE DISCRIMINATED UNION FROM CONFIG
type EventConfig = { click: { x: number; y: number }; keypress: { key: string } };
type Event = { [K in keyof EventConfig]: { type: K } & EventConfig[K] }[keyof EventConfig];

// Real-world: Effect-TS generates tagged unions from config objects
type TaggedEnum<A> = { [K in keyof A]: { readonly _tag: K } & A[K] }[keyof A];
type AppEvent = TaggedEnum<{ Click: { x: number }; Key: { code: string } }>;
// { _tag: 'Click'; x: number } | { _tag: 'Key'; code: string }

Resources

Practice

Hints

  • Think about using the never type in the default case of a switch statement to catch missing cases at compile time.
  • Try creating a discriminated union with a "type" field and use a switch statement to narrow the type.