0Pricing
TypeScript Academy · Lesson

Discriminated Unions for Safe Pattern Matching

Add a common literal field to union members for type safety.

Discriminated Unions for Safe Pattern Matching is a free TypeScript Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the TypeScript Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Welcome

Discriminated unions add a shared literal property to union members. TypeScript uses this discriminant to narrow the type in switch and if statements.

The Discriminant Property

A discriminant is a property with a unique literal type in each union member. TypeScript narrows the union based on its value.
type Circle = { kind: 'circle'; radius: number };
type Square = { kind: 'square'; side: number };
type Shape = Circle | Square;

Narrowing with if Checks

Check the discriminant in an if statement. TypeScript narrows the type to the matching member.
function area(shape: Shape): number {
  if (shape.kind === 'circle') {
    return Math.PI * shape.radius ** 2;
  }
  return shape.side ** 2; // narrowed to Square
}

Narrowing with switch/case

switch statements work perfectly with discriminated unions. Each case narrows to a specific member.
function describe(shape: Shape): string {
  switch (shape.kind) {
    case 'circle': return `Circle r=${shape.radius}`;
    case 'square': return `Square s=${shape.side}`;
  }
}

Exhaustiveness with never

Add a default case that assigns to `never`. If you add a new union member and forget to handle it, TypeScript reports an error.
function area(shape: Shape): number {
  switch (shape.kind) {
    case 'circle': return Math.PI * shape.radius ** 2;
    case 'square': return shape.side ** 2;
    default:
      const _exhaustive: never = shape;
      throw new Error('Unhandled shape');
  }
}

Result Type Pattern

Discriminated unions are perfect for the Result pattern — returning either success data or an error without throwing.
type Ok<T> = { ok: true; value: T };
type Err = { ok: false; error: string };
type Result<T> = Ok<T> | Err;

Action Type Pattern (Redux-style)

In Redux and similar systems, actions are discriminated unions. The `type` field is the discriminant.
type Action =
  | { type: 'INCREMENT'; amount: number }
  | { type: 'DECREMENT'; amount: number }
  | { type: 'RESET' };

Multiple Discriminant Properties

A discriminant doesn't have to be a single property — TypeScript can narrow on any combination of checks.
type AdminUser = { role: 'admin'; permissions: string[] };
type RegularUser = { role: 'user'; credits: number };
type User = AdminUser | RegularUser;

Non-Discriminated Unions Still Narrow

Even without a discriminant, TypeScript narrows unions using typeof, instanceof, and property checks.
type StringOrArr = string | string[];
function flatten(val: StringOrArr): string[] {
  return Array.isArray(val) ? val : [val];
}

Discriminated Unions vs Class Hierarchies

Discriminated unions are a functional alternative to class inheritance for modeling variants. They are simpler, serializable, and work well with pattern matching.

Real-World: HTTP Response Union

Model different API response states as a discriminated union.
type ApiState<T> =
  | { status: 'loading' }
  | { status: 'success'; data: T }
  | { status: 'error'; message: string };

Quick Check

What must each member of a discriminated union have for TypeScript to narrow correctly?

Recap

Discriminated unions use a shared literal property as a discriminant. Narrow with switch/case and add a never exhaustiveness check to catch unhandled cases. They are ideal for state machines, actions, and API responses.

Frequently asked questions

Is the “Discriminated Unions for Safe Pattern Matching” lesson free?

Yes — the full text of “Discriminated Unions for Safe Pattern Matching” is free to read here on the web, and the TypeScript Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the TypeScript Academy course, upgrade to CoddyKit PRO.

What will I learn in “Discriminated Unions for Safe Pattern Matching”?

Add a common literal field to union members for type safety. You practise TypeScript Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start TypeScript Academy?

No prior experience is required. TypeScript Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Discriminated Unions for Safe Pattern Matching” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this TypeScript Academy lesson?

Yes. Every TypeScript Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Union Types: A or B
  2. Intersection Types: A and B
  3. Discriminated Unions for Safe Pattern Matching
  4. Practical Patterns with Union and Intersection
← Back to TypeScript Academy