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
switchwhose value has a closed set as its declared type (also in another file), and aswitch (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 anOptable as itsop(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 ofOp. A member of a class instance declaredMut<C>,Readonly<C>orMut<Readonly<C>>has its declared type, as forC. Adefaultthat does something else (return "red") is reported too: it takes the members added later.Not reported: a
switchon a plainstringornumber, and aswitch (x.tag)wheretagis declared a plainstring(type El = { tag: string }): that is no enum's tag. (A plain string compared with many words isstring-dispatch's.) Aswitchon anumberwhose cases are the constants of one object isexhaustive-dispatch's, sinceunreachablecan't compile there.Not reported either: a
switchwithout adefaultthat has acasefor every member, when it is the last statement of a function whose declared return type can't beundefined(string, an object type,Light,Promise<number>for anasyncfunction; notvoid,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.matchis still the form to write: it says the same in one expression, and doesn't depend on theswitchstaying the last statement.✅ Also accepted: a
switchTypeScript already checks, aftermatchabove✓ Accepted0 diagnosticstsexport 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"; } }ifand?: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 (orthrow,continue,break, a call of std'sunreachableorpanic, also renamed, through aconstcopy, or as.call/.apply; not a function of that name from another module, which may return),if (x === A || x === B) ...too, and aconstholding such a test (const aloft = x === A || x === B; if (aloft) return;);- an enclosing
if (x !== A),&&or?:branch; - a
switchon the value before it, past which only the members whosecasedoesn't return get (and the ones without acase, where it has nodefault); - a
caseof an enclosingswitchon the value: only its labels get here, and those of thecases that fall into it. A member added later can't get here either: where every label has acase, 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 = otherforcmd.type), also by a destructuring assignment,++,deleteor a new declaration (aconstin 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'smutimported under another name,std.mut(...), aconstcopy ofmut, and a loan anywhere in the arguments, liketouch({ unit: mut(u) })), a method called on a part of the path (cmd.reset(), alsocmd.reset.call(cmd)and through aconstcopy ofcmd) or on something that isn't a name (units[i].stop()), anawaitor ayield. 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,awaitoryield; - 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.