0Pricing
TypeScript Academy · Lesson

Exhaustive error handling with discriminated unions

Write exhaustive handlers for discriminated unions using switch+never, helper utilities, and compile-time coverage checks across modules.

Exhaustive error handling with discriminated unions is a free TypeScript Academy lesson on CoddyKit — lesson 2 of 2. 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 2 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Intro

Goal: Guarantee every union member is handled. You will use switch + never, a tiny exhaustiveCheck utility, and see how to keep coverage across files.

  • Discriminants (tag fields)
  • Exhaustive switches
  • Fail-fast defaults

Discriminated union

A discriminated union has a shared tag (here kind). Each variant carries its own data.

export type Payment =
  | { kind: "Card"; last4: string }
  | { kind: "Cash" }
  | { kind: "Wire"; iban: string }

Switch + never

The default assigns p to never. If you add a new variant later, the compiler errors until you handle it.

export function describe(p: Payment): string {
  switch (p.kind) {
    case "Card": return `Card ••••${p.last4}`
    case "Cash": return "Cash"
    case "Wire": return `Wire ${p.iban}`
    default: {
      const _exhaustive: never = p
      return _exhaustive
    }
  }
}

exhaustiveCheck helper

Use a tiny helper to make the intent obvious. The never parameter makes unhandled cases a type error, not just a runtime throw.

export function exhaustiveCheck(x: never): never {
  throw new Error(`Unhandled case: ${JSON.stringify(x)}`)
}

export function pay(p: Payment): string {
  switch (p.kind) {
    case "Card": return "charged card"
    case "Cash": return "took cash"
    case "Wire": return "initiated wire"
    default: return exhaustiveCheck(p)
  }
}

Cross-module coverage

When unions are defined in one file and handled in another, an added branch still breaks builds until all switches are updated—exactly what we want.

// errors.ts
export type AppError =
  | { tag: "Auth"; reason: "Unauthorized" | "Forbidden" }
  | { tag: "NotFound"; resource: string }
  | { tag: "Conflict"; resource: string }

// handler.ts
import type { AppError } from "./errors"
import { exhaustiveCheck } from "./exhaustive"

export function toStatus(e: AppError): number {
  switch (e.tag) {
    case "Auth": return e.reason === "Unauthorized" ? 401 : 403
    case "NotFound": return 404
    case "Conflict": return 409
    default: return exhaustiveCheck(e)
  }
}

Tips & pitfalls

Tips:

  • Prefer string literal tags (e.g., tag/kind).
  • Keep variants small; compose data via nested objects instead of huge unions.
  • Never use default without a never guard; it hides missing cases.

Exhaustiveness check

Quick check: What enforces exhaustive handling?

Recap

Recap: Use a discriminant, write a switch, and in the default branch assign to never (or call exhaustiveCheck) to guarantee full coverage as unions evolve.

Frequently asked questions

Is the “Exhaustive error handling with discriminated unions” lesson free?

Yes — the full text of “Exhaustive error handling with discriminated unions” is free to read here on the web, and the TypeScript Academy course includes 2 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 “Exhaustive error handling with discriminated unions”?

Write exhaustive handlers for discriminated unions using switch+never, helper utilities, and compile-time coverage checks across modules. 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 2 of 2, so you can start here or from the beginning and move at your own pace.

How long does the “Exhaustive error handling with discriminated unions” 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. Result/Either style types
  2. Exhaustive error handling with discriminated unions
← Back to TypeScript Academy