Exhaustiveness checking with never

Intermediate · 10 min

Using the never type to make the compiler flag every switch that forgets a union member, including ones added long after the code was written.

Before thisDiscriminated unionsany, unknown, never, and void

Andrew Burgess · 10 min · from 5:16

Exhaustiveness checking with never

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Andrew BurgessReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • The real risk with a `switch` over a union is not today's code but next month's: someone adds a member to the union, and every `switch` that should handle it compiles without complaint.
  • Narrowing removes one member per handled case, so once every member has been handled, the value's type in the `default` branch is `never`, the type with no values.
  • Assigning the value to a variable typed `never` in the `default` branch compiles only while every case is covered; a missing case leaves a real type there, and the assignment becomes an error that names it.
  • An `assertNever(value: never): never` helper does the same check at compile time and throws at runtime, which also catches values the types didn't predict, such as a new status from an API.
  • A function with a declared return type and no `default` gets a weaker form of the check for free, through the "lacks ending return statement" error.
  • When each member maps to a value rather than to code, a `Record<Union, Value>` object is exhaustive by construction, because a missing key is a type error.

The bug that arrives later

The discriminated unions lesson ended with a switch that handles each member of a union. Written today, it’s correct. The problem comes later:

type Shape =
  | { kind: "circle"; radius: number }
  | { kind: "square"; side: number }
  | { kind: "triangle"; base: number; height: number }; // added last week

Somebody adds triangle. The type changes in one file. Meanwhile area, perimeter, draw, and a dozen other functions across the codebase each switch on kind, and none of them know about triangles. If those functions don’t return a value in every branch, nothing fails to compile. The bug shows up at runtime, wherever a triangle first reaches one of them.

What you want is for the compiler to visit every one of those switches and tell you which ones need updating. The tool for that is never.

Narrowing all the way down

Watch what narrowing does inside a switch. Each case removes the member it matched from the union for the code after it. After case "circle" and case "square", the only thing left in default is the triangle member. Handle that too, and nothing is left.

A union with nothing left in it is never, the type with no values. That gives you a test: in the default branch, is the value’s type never? If yes, every member was handled. If no, whatever is left is exactly what you forgot.

Making the compiler check it

Turn that test into code by assigning the value to a variable typed never. Only never itself is assignable to never:

function area(shape: Shape): number {
  switch (shape.kind) {
    case "circle":
      return Math.PI * shape.radius ** 2;
    case "square":
      return shape.side ** 2;
    default: {
      const unhandled: never = shape;
      // error: Type '{ kind: "triangle"; base: number; height: number; }'
      //        is not assignable to type 'never'.
      throw new Error(`Unhandled shape: ${JSON.stringify(unhandled)}`);
    }
  }
}

The error message names the missing member. Add case "triangle" and the error disappears, because shape in default is now never. Every function with this line becomes a checklist the compiler fills in for you whenever the union grows.

Writing shape satisfies never; in the default branch is a shorter spelling of the same check, using the satisfies operator from later in this group.

The assertNever helper

Most codebases wrap the pattern in a function:

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

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

The never parameter gives the compile-time check. The throw covers the runtime gap, because types describe what you expect, not what actually arrives. If a server starts sending kind: "hexagon" before your types know about it, assertNever fails loudly with the bad value, instead of area quietly returning undefined.

A free, weaker version

If a function has an explicit return type and every case returns, leaving out default already gets you something:

function sides(shape: Shape): number {
  // error: Function lacks ending return statement and
  //        return type does not include 'undefined'.
  switch (shape.kind) {
    case "circle":
      return 0;
    case "square":
      return 4;
  }
}

A missing case means the function can fall off the end. It’s a real check, but it doesn’t name the missing member, and it disappears for a switch that doesn’t return, such as one that logs or dispatches. The explicit never check works in both.

When a table beats a switch

Sometimes each member just maps to a value. A Record keyed by the union is exhaustive by construction:

type Level = "debug" | "info" | "warn" | "error";

const colors: Record<Level, string> = {
  debug: "gray",
  info: "blue",
  warn: "yellow",
};
// error: Property 'error' is missing in type '{ debug: string; info: string; warn: string; }'
//        but required in type 'Record<Level, string>'.

Add a level to the union and this object fails to compile until it gets a colour. Use a switch with never when each member needs different logic; use a Record when it needs a different value.

About the video

Andrew Burgess builds a structured union, narrows it with switch, and then gets to the “exhaustive switch pattern”: assigning to never in the default case so that a new union member becomes a compile error. The embed starts at that chapter (5:16). If you want the setup first, scrub back. The first five minutes revisit discriminated unions, a useful refresher after the previous lesson. The video ends at 8:51 with an unrelated bonus on intersection types, which you can skip. Hitesh Choudhary’s video, linked below, follows the TypeScript handbook’s version of the same material.

Check yourself

  1. 01Why is the type of `shape` `never` in the `default` branch of a `switch` that handles every member of a union?

    Each `case` that matches a member removes it from the union for the code that follows. Once every member has been removed, no possible value could reach `default`, and the type with no possible values is `never`.

  2. 02How does `const unhandled: never = shape;` in a `default` branch catch a missing case?

    Only `never` is assignable to `never`. If a case is missing, the narrowed type in `default` is that unhandled member, not `never`, so the assignment fails with an error naming the member's type. Once you add the case, the error goes away.

  3. 03What does an `assertNever` helper give you beyond the bare `never` assignment?

    It is a reusable function whose parameter is typed `never`, so calls to it give the same compile-time check. Because it throws, it also fails loudly at runtime if a value the types didn't anticipate arrives anyway, for example an unknown status from a server.

  4. 04A function declared to return `number` switches over `"circle" | "square" | "triangle"` but only has cases for two of them and no `default`. What error does TypeScript report, and why is this weaker than the `never` check?

    It reports "Function lacks ending return statement and return type does not include 'undefined'", because the missing case falls off the end. It's weaker because it only works when every case returns and the function has an explicit return type, and the message doesn't say which member was missed.

  5. 05When is a `Record<Level, string>` lookup table a better exhaustiveness tool than a `switch`?

    When each union member maps to a plain value, such as a colour or label, rather than to different logic. The `Record` type requires a key for every member of `Level`, so forgetting one, or adding a new member to the union later, is a type error at the object literal.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark