Lesson 9 of 11 · 12 min

Discriminated unions

Real data often comes in a few different shapes. A payment might be cash, card or mobile money, and each needs different fields. A discriminated union models this with a shared literal property (the discriminant) that says which shape you have:

type Payment =
  | { method: "cash" }
  | { method: "card"; last4: string }
  | { method: "mobile"; phone: string; network: "EcoCash" | "OneMoney" };

Checking the discriminant narrows to the right shape, so TypeScript knows which fields exist:

function describe(p: Payment): string {
  switch (p.method) {
    case "cash":
      return "Cash";
    case "card":
      return `Card ending ${p.last4}`;          // p is the card shape here
    case "mobile":
      return `${p.network} ${p.phone}`;         // and the mobile shape here
  }
}

Proving every case is handled

The type never means "this cannot happen". After every case is handled, the value in the default branch has type never. If someone later adds a new shape and forgets to handle it, the value is no longer never and the assignment becomes a type error, pointing straight at the place to fix:

default: {
  const unreachable: never = p;
  throw new Error(`Unknown payment: ${JSON.stringify(unreachable)}`);
}

This turns "I hope I updated every switch" into a compiler guarantee.

Your task

  1. Add a triangle to Shape: { kind: "triangle"; base: number; height: number }.
  2. Make area handle it (base times height divided by 2), keeping the never check so there are no type errors.
main.ts
type Shape =
  | { kind: "circle"; radius: number }
  | { kind: "rectangle"; width: number; height: number };

function area(shape: Shape): number {
  switch (shape.kind) {
    case "circle":
      return Math.PI * shape.radius * shape.radius;
    case "rectangle":
      return shape.width * shape.height;
    default: {
      const unreachable: never = shape;
      throw new Error(`Unknown shape: ${JSON.stringify(unreachable)}`);
    }
  }
}

console.log(area({ kind: "triangle", base: 6, height: 5 }));

TypeScript 5.9 runs right here in your browser. The first run downloads about 1.5 MB; after that it is instant.

Discussion

Stuck? Ask here. Be kind, and share hints rather than full answers.

Loading the discussion…