How TypeScript's never Type Catches a Forgotten switch Case Before Code RunsBrief · digest for November 28
Brief≈ 1 min

How TypeScript's never Type Catches a Forgotten switch Case Before Code Runs

An order used to have "paid" and "shipped" statuses, and then the business added "refunded". You add it to the union type (the list of allowed values) and update a couple of files. The project builds cleanly, yet in production a refunded order shows a blank label because one old switch was missed.

TypeScript prevents this with exhaustiveness checking via never. In each case, the compiler narrows the variable's type and eliminates handled options. If all are covered, default leaves never—an "empty" type for impossible states. It can be assigned to any type, while only never can be assigned to it.

type Status = "paid" | "shipped" | "refunded";

function label(status: Status): string {
  switch (status) {
    case "paid":
      return "Paid";
    case "shipped":
      return "Shipped";
    default: {
      // Error: Type '"refunded"' is not assignable to type 'never'
      const unhandled: never = status;
      return unhandled;
    }
  }
}

Until a "refunded" branch is added, status inside default keeps that type, so your editor flags the assignment in red right away. This check only runs at type-check time: if unvalidated server data arrives cast with as Status, throw an error in production using an assertNever(x: never): never helper.

Want a deep diveVotes help us choose what to break down in detail. This material has 0 votes.
Sources · 2