JavaScript and TypeScript course ยท Module 7: Advanced TypeScript

Discriminated Unions and Pattern Matching

7 min read ยท
In this lesson6

"In the Jurassic Park control center, every situation requires a different response," explains Claire Dearing, the park's operations director. "A dinosaur escape, a power failure, a visitor injury - each incident has its own protocol. We can't mix one up with another, because the consequences would be catastrophic. The system must identify the event type on its own and direct us to the correct procedure."

Discriminated unions are a powerful TypeScript pattern in which each variant of a union has a common field - a discriminator (tag) - that uniquely identifies the type. Combined with pattern matching based on switch, they create an elegant, safe, and extensible system for handling different states and events.

Discriminated unions basics

A discriminated union is a union of types where each type has a field with the same name (tag) but with a different literal value. TypeScript can narrow the type based on the value of this field.

// The "status" field is the discriminator
interface ActiveDinosaur {
  status: "active";
  name: string;
  enclosureId: string;
  lastFed: Date;
}

interface SleepingDinosaur {
  status: "sleeping";
  name: string;
  enclosureId: string;
  sleepStarted: Date;
  estimatedWakeUp: Date;
}

interface SickDinosaur {
  status: "sick";
  name: string;
  enclosureId: string;
  diagnosis: string;
  veterinarianId: string;
}

type DinosaurState = ActiveDinosaur | SleepingDinosaur | SickDinosaur;

// TypeScript narrows the type after checking the status field
function getDinosaurReport(dino: DinosaurState): string {
  switch (dino.status) {
    case "active":
      // TypeScript knows this is ActiveDinosaur - we have access to lastFed
      return `${dino.name}: Active, last feeding: ${dino.lastFed.toLocaleString()}`;
    case "sleeping":
      // TypeScript knows this is SleepingDinosaur - we have access to estimatedWakeUp
      return `${dino.name}: Sleeping, estimated wake-up: ${dino.estimatedWakeUp.toLocaleString()}`;
    case "sick":
      // TypeScript knows this is SickDinosaur - we have access to diagnosis
      return `${dino.name}: Sick - ${dino.diagnosis}, veterinarian: ${dino.veterinarianId}`;
  }
}

Key aspects of discriminated unions:

  1. The common field (tag/discriminator) must have a literal type (e.g., "active", not string)
  2. Each variant has a unique tag value
  3. TypeScript automatically narrows the type after checking the tag value

Pattern matching with switch

The switch construct is a natural tool for pattern matching in TypeScript. Each case corresponds to one variant of the discriminated union.

// Jurassic Park event system
interface FeedingEvent {
  type: "feeding";
  dinosaurId: string;
  food: string;
  amountKg: number;
  timestamp: Date;
}

interface EscapeEvent {
  type: "escape";
  dinosaurId: string;
  enclosureId: string;
  breachType: "fence" | "gate" | "underground";
  timestamp: Date;
}

interface MaintenanceEvent {
  type: "maintenance";
  systemId: string;
  description: string;
  priority: "low" | "medium" | "high" | "critical";
  timestamp: Date;
}

interface VisitorEvent {
  type: "visitor";
  visitorCount: number;
  zone: string;
  eventKind: "entry" | "exit" | "emergency";
  timestamp: Date;
}

type ParkEvent = FeedingEvent | EscapeEvent | MaintenanceEvent | VisitorEvent;

// Pattern matching - handling each event type
function processParkEvent(event: ParkEvent): { action: string; urgency: number } {
  switch (event.type) {
    case "feeding":
      return {
        action: `Feeding ${event.dinosaurId}: ${event.amountKg}kg ${event.food}`,
        urgency: 1
      };

    case "escape":
      return {
        action: `ALARM! ${event.dinosaurId} escaped from ${event.enclosureId} (type: ${event.breachType})`,
        urgency: 10
      };

    case "maintenance":
      const urgencyMap = { low: 2, medium: 4, high: 7, critical: 9 };
      return {
        action: `Maintenance ${event.systemId}: ${event.description}`,
        urgency: urgencyMap[event.priority]
      };

    case "visitor":
      const visitorUrgency = event.eventKind === "emergency" ? 8 : 1;
      return {
        action: `Visitors (${event.visitorCount}) in ${event.zone}: ${event.eventKind}`,
        urgency: visitorUrgency
      };
  }
}

Exhaustive handling - guaranteeing all variants are handled

One of the greatest advantages of discriminated unions is the possibility of exhaustive handling - the compiler can check whether you've handled ALL variants. If you add a new type to the union, TypeScript will immediately point out all places that need updating.

// Helper for exhaustive check
function assertNever(value: never, message?: string): never {
  throw new Error(message || `Unhandled variant: ${JSON.stringify(value)}`);
}

// If we add a new event type to ParkEvent and forget to handle it,
// TypeScript will report an error in the default clause
function processEventStrict(event: ParkEvent): string {
  switch (event.type) {
    case "feeding":
      return "Feeding";
    case "escape":
      return "Escape";
    case "maintenance":
      return "Maintenance";
    case "visitor":
      return "Visitors";
    default:
      // If a case were missing, TypeScript would report an error:
      // "Type 'XXX' is not assignable to type 'never'"
      return assertNever(event);
  }
}

State machines with discriminated unions

Discriminated unions are perfectly suited for modeling state machines, where an object can be in one of several states, and transitions between states are strictly controlled.

// Dinosaur enclosure states as a state machine
interface EnclosureNormal {
  state: "normal";
  dinosaurCount: number;
  securityLevel: number;
}

interface EnclosureLockdown {
  state: "lockdown";
  dinosaurCount: number;
  securityLevel: number;
  reason: string;
  lockdownSince: Date;
}

interface EnclosureBreach {
  state: "breach";
  dinosaurCount: number;
  escapedCount: number;
  breachLocation: string;
  responseTeamDispatched: boolean;
}

interface EnclosureMaintenance {
  state: "maintenance";
  dinosaurCount: 0; // Enclosure must be empty during maintenance
  scheduledEnd: Date;
  maintenanceType: string;
}

type EnclosureState = EnclosureNormal | EnclosureLockdown | EnclosureBreach | EnclosureMaintenance;

// Allowed transitions between states
function transitionEnclosure(
  current: EnclosureState,
  action: "lockdown" | "breach" | "repair" | "resolve"
): EnclosureState {
  switch (current.state) {
    case "normal":
      if (action === "lockdown") {
        return {
          state: "lockdown",
          dinosaurCount: current.dinosaurCount,
          securityLevel: current.securityLevel + 5,
          reason: "Security procedure",
          lockdownSince: new Date()
        };
      }
      if (action === "repair") {
        if (current.dinosaurCount > 0) {
          throw new Error("Cannot start maintenance - enclosure occupied!");
        }
        return {
          state: "maintenance",
          dinosaurCount: 0,
          scheduledEnd: new Date(Date.now() + 86400000),
          maintenanceType: "Standard inspection"
        };
      }
      return current;

    case "lockdown":
      if (action === "breach") {
        return {
          state: "breach",
          dinosaurCount: current.dinosaurCount - 1,
          escapedCount: 1,
          breachLocation: "Unknown sector",
          responseTeamDispatched: false
        };
      }
      if (action === "resolve") {
        return {
          state: "normal",
          dinosaurCount: current.dinosaurCount,
          securityLevel: current.securityLevel
        };
      }
      return current;

    case "breach":
      if (action === "resolve") {
        return {
          state: "lockdown",
          dinosaurCount: current.dinosaurCount + current.escapedCount,
          securityLevel: 10,
          reason: "Post-breach lockdown",
          lockdownSince: new Date()
        };
      }
      return current;

    case "maintenance":
      if (action === "resolve") {
        return {
          state: "normal",
          dinosaurCount: 0,
          securityLevel: 5
        };
      }
      return current;
  }
}

// State machine test
let enclosure: EnclosureState = {
  state: "normal",
  dinosaurCount: 3,
  securityLevel: 5
};

console.log("Initial state:", enclosure.state);
enclosure = transitionEnclosure(enclosure, "lockdown");
console.log("After lockdown:", enclosure.state);
enclosure = transitionEnclosure(enclosure, "breach");
console.log("After breach:", enclosure.state);
if (enclosure.state === "breach") {
  console.log("Escaped dinosaurs:", enclosure.escapedCount);
}

API responses as discriminated unions

A common real-world application is modeling API responses using discriminated unions:

// Generic API response type
interface SuccessResponse<T> {
  status: "success";
  data: T;
  timestamp: Date;
}

interface ErrorResponse {
  status: "error";
  errorCode: number;
  message: string;
  timestamp: Date;
}

interface LoadingResponse {
  status: "loading";
  progress: number; // 0-100
}

type ApiResponse<T> = SuccessResponse<T> | ErrorResponse | LoadingResponse;

// Dinosaur API data type
interface DinosaurApiData {
  id: string;
  name: string;
  species: string;
  weight: number;
}

// Response handling with full type safety
function renderDinosaurData(response: ApiResponse<DinosaurApiData>): string {
  switch (response.status) {
    case "loading":
      return `Loading... ${response.progress}%`;
    case "error":
      return `Error ${response.errorCode}: ${response.message}`;
    case "success":
      const { name, species, weight } = response.data;
      return `${name} (${species}) - ${weight} kg`;
  }
}

// Test responses
const loading: ApiResponse<DinosaurApiData> = { status: "loading", progress: 45 };
const success: ApiResponse<DinosaurApiData> = {
  status: "success",
  data: { id: "D-001", name: "Rexy", species: "T-Rex", weight: 8000 },
  timestamp: new Date()
};
const error: ApiResponse<DinosaurApiData> = {
  status: "error",
  errorCode: 404,
  message: "Dinosaur not found",
  timestamp: new Date()
};

console.log(renderDinosaurData(loading));
console.log(renderDinosaurData(success));
console.log(renderDinosaurData(error));

Summary

Discriminated unions and pattern matching are among the most powerful patterns in TypeScript:

  1. Discriminated unions - each variant has a common field (tag) with a unique literal value
  2. Pattern matching with switch - elegant handling of all variants
  3. Exhaustive handling with never - the compiler ensures you've handled every variant
  4. State machines - modeling allowed transitions between states
  5. API responses - typing success/error/loading with full safety

As Claire Dearing says: "In Jurassic Park, every scenario has its protocol. With discriminated unions, TypeScript ensures that no scenario is overlooked. It's like an early warning system - it doesn't allow any threat to be missed."

Code for this lesson: index.ts
// Discriminated unions and pattern matching - Jurassic Park
console.log("=== DISCRIMINATED UNIONS ===\n");

// ===========================================
// 1. A basic discriminated union
// ===========================================

interface ActiveDino {
  status: "active";
  name: string;
  lastFed: string;
}

interface SleepingDino {
  status: "sleeping";
  name: string;
  wakeUpAt: string;
}

interface SickDino {
  status: "sick";
  name: string;
  diagnosis: string;
}

type DinoState = ActiveDino | SleepingDino | SickDino;

function getReport(dino: DinoState): string {
  switch (dino.status) {
    case "active": return `${dino.name}: active, fed at ${dino.lastFed}`;
    case "sleeping": return `${dino.name}: sleeping, wakes up at ${dino.wakeUpAt}`;
    case "sick": return `${dino.name}: sick - ${dino.diagnosis}`;
  }
}

console.log("--- Dinosaur status ---");
console.log(getReport({ status: "active", name: "Rexy", lastFed: "10:00" }));
console.log(getReport({ status: "sleeping", name: "Blue", wakeUpAt: "15:00" }));
console.log(getReport({ status: "sick", name: "Cera", diagnosis: "Fever" }));

// ===========================================
// 2. An event system with pattern matching
// ===========================================

interface FeedEvent { type: "feed"; dinoId: string; food: string; kg: number; }
interface EscapeEvent { type: "escape"; dinoId: string; zone: string; }
interface MaintenanceEvent { type: "maintenance"; system: string; priority: "low" | "high"; }

type ParkEvent = FeedEvent | EscapeEvent | MaintenanceEvent;

function processEvent(event: ParkEvent): { action: string; urgency: number } {
  switch (event.type) {
    case "feed":
      return { action: `Feeding ${event.dinoId}: ${event.kg}kg of ${event.food}`, urgency: 1 };
    case "escape":
      return { action: `ALARM! ${event.dinoId} escaped from ${event.zone}!`, urgency: 10 };
    case "maintenance":
      return { action: `Maintenance: ${event.system}`, urgency: event.priority === "high" ? 7 : 3 };
  }
}

console.log("\n--- Events ---");
const events: ParkEvent[] = [
  { type: "feed", dinoId: "D-01", food: "goat", kg: 50 },
  { type: "escape", dinoId: "D-03", zone: "Sector B" },
  { type: "maintenance", system: "Fence A", priority: "high" },
];
events.forEach(e => {
  const r = processEvent(e);
  console.log(`[${r.urgency}] ${r.action}`);
});

// ===========================================
// 3. Exhaustive check with never
// ===========================================

function assertNever(value: never, msg?: string): never {
  throw new Error(msg || "Unhandled variant: " + JSON.stringify(value));
}

function strictProcess(event: ParkEvent): string {
  switch (event.type) {
    case "feed": return "Feeding";
    case "escape": return "Escape";
    case "maintenance": return "Maintenance";
    default: return assertNever(event);
  }
}

console.log("\n--- Exhaustive check ---");
console.log("All variants handled:", strictProcess(events[0]));

// ===========================================
// 4. An enclosure state machine
// ===========================================

interface NormalState { state: "normal"; dinoCount: number; }
interface LockdownState { state: "lockdown"; dinoCount: number; reason: string; }
interface BreachState { state: "breach"; escaped: number; }

type EncState = NormalState | LockdownState | BreachState;

function transition(current: EncState, action: "lock" | "breach" | "resolve"): EncState {
  switch (current.state) {
    case "normal":
      if (action === "lock") return { state: "lockdown", dinoCount: current.dinoCount, reason: "Procedure" };
      return current;
    case "lockdown":
      if (action === "breach") return { state: "breach", escaped: 1 };
      if (action === "resolve") return { state: "normal", dinoCount: current.dinoCount };
      return current;
    case "breach":
      if (action === "resolve") return { state: "lockdown", dinoCount: 0, reason: "Post-breach" };
      return current;
  }
}

console.log("\n--- State machine ---");
let enc: EncState = { state: "normal", dinoCount: 3 };
console.log("Start:", enc.state);
enc = transition(enc, "lock");
console.log("After lock:", enc.state);
enc = transition(enc, "breach");
console.log("After breach:", enc.state);
enc = transition(enc, "resolve");
console.log("After resolve:", enc.state);

// ===========================================
// 5. API Response pattern
// ===========================================

interface Success<T> { status: "ok"; data: T; }
interface Err { status: "error"; code: number; message: string; }
interface Loading { status: "loading"; progress: number; }

type ApiResponse<T> = Success<T> | Err | Loading;

function render(res: ApiResponse<{ name: string }>): string {
  switch (res.status) {
    case "loading": return `Loading... ${res.progress}%`;
    case "error": return `Error ${res.code}: ${res.message}`;
    case "ok": return `Data: ${res.data.name}`;
  }
}

console.log("\n--- API Response ---");
console.log(render({ status: "loading", progress: 50 }));
console.log(render({ status: "ok", data: { name: "Rexy" } }));
console.log(render({ status: "error", code: 404, message: "Not found" }));

console.log("\nDiscriminated unions = safe pattern matching!");

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. What is a discriminated union in TypeScript?

  2. 2. What is the purpose of the never type in the default clause of a switch statement when handling a discriminated union?

These are 2 of 4 questions for this lesson. Solve the rest in the game.

Hands-on tasks in the game

  • Horizontal ordering

    Arrange the elements of a discriminated union type:

  • Code editor

    Create a discriminated union with pattern matching and exhaustive check for park events

  • Horizontal ordering

    Arrange the elements of Omit usage:

  • Horizontal ordering

    Arrange the elements of Record usage:

  • Code editor

    Create a complete type system for park management

  • Horizontal ordering

    Arrange the elements of Required usage:

  • Horizontal ordering

    Arrange the elements of the Pick type:

  • Vertical ordering

    Order the evolution from a simple type to an advanced utility type:

  1. QuestionDiscriminated Union
  2. Put in orderDiscriminated Union Syntax
  3. Coding taskDiscriminated Unions - Practice
  4. QuestionExhaustive Check with never
  5. QuestionPractical Use of Omit
  6. Put in orderOmit Syntax
  7. QuestionWhat Does Record<K, T> Do
  8. Put in orderRecord Syntax
  9. Coding taskAdvanced Type System - Practice
  10. Put in orderRequired Syntax
  11. Put in orderPick Syntax
  12. Put in orderFrom Type to Generic Utility

Useful articles