Course contentsShow
← TypeScript
Lesson 424 of 1,7969. Union TypesFree lesson

Adding New Union Variants Safely

How exhaustive checks force you to update all switch statements when adding a new variant to a union type.

Adding New Union Variants Safely

What you'll learn: How exhaustive checks force you to update all switch statements when adding a new variant to a union type.

When you use exhaustive checking (with never and a helper like assertNever), TypeScript becomes your safety net during code evolution. If you add a new variant to a discriminated union, every switch statement that handles that union will immediately fail to compile until you handle the new case.

The Safety Mechanism

Imagine you have a union type representing different shapes:

type Shape = 
  | { kind: "circle"; radius: number }
  | { kind: "square"; size: number };

function assertNever(value: never): never {
  throw new Error(`Unexpected value: ${value}`);
}

function getArea(shape: Shape): number {
  switch (shape.kind) {
    case "circle":
      return Math.PI * shape.radius ** 2;
    case "square":
      return shape.size ** 2;
    default:
      return assertNever(shape); // TypeScript knows shape is never here
  }
}

Now, add a new variant:

type Shape = 
  | { kind: "circle"; radius: number }
  | { kind: "square"; size: number }
  | { kind: "triangle"; base: number; height: number }; // New!

TypeScript immediately errors at assertNever(shape) because shape could now be a triangle, not never. You cannot compile until you add the triangle case. This prevents you from shipping incomplete code.

Why This Matters

Without exhaustive checks, you could add new union variants and silently break existing code at runtime. With them, TypeScript forces you to update every relevant location before your code even runs.

Key Takeaway: Exhaustive checks with never turn adding union variants into a compile-time error, forcing you to update all handlers and preventing runtime bugs.