Skip to content

exhaustive-switch ​

A switch on a closed set has no default: unreachable(value). A closed set is an enum's tag (switch (x.tag)), a union of string or number literals, or the constants of a code object (type Phase = (typeof Phase)[keyof typeof Phase]), as the value's declared type says.

Why: without it, a member added later silently falls through the switch, or takes its default. With it, TypeScript proves every member is handled: unreachable only accepts never, and the value only narrows to never when all cases are covered. The message names the members without a case. Guide: Enums.

✕ Rejectedexhaustive-switch
ts
import type { Enum } from "@evobug_com/safe-ts-std/enum";

type Payment = Enum<{ Card: { last4: string }; Invoice: { days: number } }>;

export function describe(payment: Payment): string {
  switch (payment.tag) {
    case "Card":
      return `card ending ${payment.last4}`;
    case "Invoice":
      return `invoice, ${payment.days} days`;
  }
  return "";
}

✅ Accepted: match

✓ Accepted0 diagnostics
ts
import { type Enum, match } from "@evobug_com/safe-ts-std/enum";

type Payment = Enum<{ Card: { last4: string }; Invoice: { days: number } }>;

export function describe(payment: Payment): string {
  return match(payment, {
    Card: ({ last4 }) => `card ending ${last4}`,
    Invoice: ({ days }) => `invoice, ${days} days`,
  });
}
ts
import { unreachable as __matchUnreachable } from "@evobug_com/safe-ts-std/enum"; import { type Enum, match } from "@evobug_com/safe-ts-std/enum";

type Payment = Enum<{ Card: { last4: string }; Invoice: { days: number } }>;

export function describe(payment: Payment): string {
  { const __ms1 = payment; let __mv1: string; switch (__ms1.tag) {
    case "Card": { const { last4 } = __ms1; __mv1 = `card ending ${last4}`; break; }
    case "Invoice": { const { days } = __ms1; __mv1 = `invoice, ${days} days`; break; } default: __mv1 = __matchUnreachable(__ms1); } return __mv1; }

}

✅ Also accepted: switch with unreachable, where the idiomatic rules are off (they ask for match instead of a switch on .tag)

✓ Accepted0 diagnostics
ts
import { type Enum, unreachable } from "@evobug_com/safe-ts-std/enum";

type Payment = Enum<{ Card: { last4: string }; Invoice: { days: number } }>;

export function describe(payment: Payment): string {
  switch (payment.tag) {
    case "Card":
      return `card ending ${payment.last4}`;
    case "Invoice":
      return `invoice, ${payment.days} days`;
    default:
      return unreachable(payment);
  }
}

The same for a union of literals:

✕ Rejectedexhaustive-switch
ts
export type Light = "red" | "amber" | "green";

export function next(light: Light): Light {
  switch (light) {
    case "red":
      return "green";
    case "green":
      return "amber";
    default:
      return "red";
  }
}

✅ Accepted: match on the union

✓ Accepted0 diagnostics
ts
import { match } from "@evobug_com/safe-ts-std/enum";

export type Light = "red" | "amber" | "green";

export function next(light: Light): Light {
  return match(light, { red: () => "green", green: () => "amber", amber: () => "red" });
}
ts
import { unreachable as __matchUnreachable } from "@evobug_com/safe-ts-std/enum"; import { match } from "@evobug_com/safe-ts-std/enum";

export type Light = "red" | "amber" | "green";

export function next(light: Light): Light {
  { const __ms1 = light; let __mv1: Light; switch (__ms1) { case "red": { __mv1 = "green"; break; } case "green": { __mv1 = "amber"; break; } case "amber": { __mv1 = "red"; break; } default: __mv1 = __matchUnreachable(__ms1); } return __mv1; }
}

✅ Also accepted: switch with unreachable, the form for a union of numbers (match takes strings and enums)

✓ Accepted0 diagnostics
ts
import { unreachable } from "@evobug_com/safe-ts-std/enum";

export type Light = "red" | "amber" | "green";

export function next(light: Light): Light {
  switch (light) {
    case "red":
      return "green";
    case "green":
      return "amber";
    case "amber":
      return "red";
    default:
      return unreachable(light);
  }
}

A member of a union of object types takes its set from the union's members. Here the client's packets are those whose dir is "c2s", so the default takes Op.Hello, and the server's Op.Welcome and Op.Pong aren't asked for (a case for one is TS2678):

✕ Rejectedexhaustive-switch
ts
export const Op = Object.freeze({ Hello: 1, Welcome: 2, Ping: 3, Pong: 4 });
type OpCode = (typeof Op)[keyof typeof Op];

const PACKETS = {
  [Op.Hello]: { dir: "c2s" },
  [Op.Welcome]: { dir: "s2c" },
  [Op.Ping]: { dir: "c2s" },
  [Op.Pong]: { dir: "s2c" },
} as const;

type ClientOp = { [O in OpCode]: (typeof PACKETS)[O]["dir"] extends "c2s" ? O : never }[OpCode];
type PacketOf<O extends OpCode> = O extends OpCode ? { op: O } : never;
export type ClientPacket = PacketOf<ClientOp>;

export function answer(p: ClientPacket): string {
  switch (p.op) {
    case Op.Ping:
      return "pong";
    default:
      return "";
  }
}

What counts ​

  • Reported: a switch whose value has a closed set as its declared type (also in another file), and a switch (x.tag) whose type can't be found, as before. The set is what the type allows: switch (p.op) on a union of packet types, each with one code of an Op table as its op (also a union derived from a table of packets by a mapped type), asks only for those packets' codes, named by the table's constants, not for every constant of Op. A member of a class instance declared Mut<C>, Readonly<C> or Mut<Readonly<C>> has its declared type, as for C. A default that does something else (return "red") is reported too: it takes the members added later.

  • Not reported: a switch on a plain string or number, and a switch (x.tag) where tag is declared a plain string (type El = { tag: string }): that is no enum's tag. (A plain string compared with many words is string-dispatch's.) A switch on a number whose cases are the constants of one object is exhaustive-dispatch's, since unreachable can't compile there.

  • Not reported either: a switch without a default that has a case for every member, when it is the last statement of a function whose declared return type can't be undefined (string, an object type, Light, Promise<number> for an async function; not void, Option<T> or a type it can't find). There a member added later falls off the end of the function, and TypeScript already rejects that: "Function lacks ending return statement and return type does not include 'undefined'". The checker reads the type as declared, following type names into other files. match is still the form to write: it says the same in one expression, and doesn't depend on the switch staying the last statement.

    ✅ Also accepted: a switch TypeScript already checks, after match above

    ✓ Accepted0 diagnostics
    ts
    export type Light = "red" | "amber" | "green";
    
    export function next(light: Light): Light {
      switch (light) {
        case "red":
          return "green";
        case "green":
          return "amber";
        case "amber":
          return "red";
      }
    }
  • if and ?: chains on a closed set: exhaustive-dispatch.

Members the code before it took ​

The message names only the members that can get to the switch. TypeScript narrows the value on the way, and a case for a member it has narrowed away doesn't compile ("Type '"bridge"' is not comparable", TS2678), so the rule follows the same tests:

  • if (x === A) return; before it (or throw, continue, break, a call of std's unreachable or panic, also renamed, through a const copy, or as .call / .apply; not a function of that name from another module, which may return), if (x === A || x === B) ... too, and a const holding such a test (const aloft = x === A || x === B; if (aloft) return;);
  • an enclosing if (x !== A), && or ?: branch;
  • a switch on the value before it, past which only the members whose case doesn't return get (and the ones without a case, where it has no default);
  • a case of an enclosing switch on the value: only its labels get here, and those of the cases that fall into it. A member added later can't get here either: where every label has a case, nothing is reported, and where one hasn't, the message doesn't say "and so would a new member".

An adopter's switch on a tool after if (tool === "bridge") return ...; was reported for "bridge", and the case the message asked for was TS2678.

✅ Not reported: "bridge" can't get to the switch

✓ Accepted0 diagnostics
ts
import { unreachable } from "@evobug_com/safe-ts-std/enum";

export type Tool = "dig" | "fill" | "bridge";

export function cost(tool: Tool, wet: boolean): number {
  if (tool === "bridge") return wet ? 5 : 0;
  switch (tool) {
    case "dig":
      return 1;
    case "fill":
      return 2;
    default:
      return unreachable(tool);
  }
}

What a test said no longer counts where the value may have changed since; the member is named again:

  • the value, or a part of its path, is assigned (x = ..., cmd = other for cmd.type), also by a destructuring assignment, ++, delete or a new declaration (a const in a loop's body), or a member of that name is written through any other name (other.type = ...);
  • for a path (cmd.type): a call that lends anything (mut(world): what is lent may hold it; also std's mut imported under another name, std.mut(...), a const copy of mut, and a loan anywhere in the arguments, like touch({ unit: mut(u) })), a method called on a part of the path (cmd.reset(), also cmd.reset.call(cmd) and through a const copy of cmd) or on something that isn't a name (units[i].stop()), an await or a yield. A call given the object without a loan (describe(cmd)) doesn't count: in a checked file a function changes only what it is lent;
  • a value something else may reach (this.mode, a module-level binding, a binding of the enclosing function) or that a function created here changes or hands on: any call, await or yield;
  • a member read that runs a getter: each read may give another value.

A test of another expression (a.b.kind for a.c.kind) says nothing, nor a test outside the function the switch is in: a callback runs later, when the value may be anything.

Quick fix: Add default: unreachable(…), where the switch has no default. Where the code before it took the members without a case, the value is never in that default, and the fix compiles.

MIT OR Apache-2.0 · Docs by Gemini 4 Neon Extra