SkillByAIOpen interactive version →

Lesson 22 / 28

Discriminated Unions

Model variants with discriminated unions and a shared literal field, and check every case with never.

A discriminated union

Give every variant a shared literal field (kind) — TS uses it to know exactly which shape you're holding.

interface Circle {
  kind: "circle";
  radius: number;
}
interface Square {
  kind: "square";
  side: number;
}
type Shape = Circle | Square;

Exhaustive switch

Switching on kind narrows each case automatically, with no manual casting.

function area(shape: Shape): number {
  switch (shape.kind) {
    case "circle":
      return Math.PI * shape.radius ** 2;
    case "square":
      return shape.side ** 2;
  }
}

Exhaustiveness checking

Add a default: const _exhaustive: never = shape; branch — if a new shape variant is ever added and not handled, TS flags it at compile time.