TypeScript example

How to check a switch is exhaustive in TypeScript

8 min read Updated Nov 2026 Runs in an isolated runtime
Quick answer

Add a default case that passes the switched value to a function taking never: function assertNever(value: never): never { throw new Error(…); }, then default: return assertNever(shape);. When every case is handled the value has narrowed to never and the call compiles. Forget a case and the build fails with error TS2345 naming the member you missed. Since TypeScript 4.9, value satisfies never does the same check without a helper.

TypeScript has no built-in "exhaustive switch" keyword, but it doesn't need one. Inside a switch over a union or an enum, every case removes its member from the value's type, and once all of them are gone the type left in the default branch is never. Anything that only accepts never there turns a forgotten case into a compile error, which is what you want the day someone adds a member to the union. The sections below cover the assertNever helper, the error it gives, two ways to write the check without a helper, the return-type check, a Record map instead of a switch, and the same check on enums and if/else chains. Each example runs on this page: hit Run, then edit the code and run it again.

1assertNever in the default caseRecommended

Write a small function whose parameter has type never and call it from the default case with the value you switched on. Switching on shape.kind narrows the whole shape object, because kind is the discriminant of the union, so you can pass either one. Return the call's result: its return type is also never, which fits any return type and tells TypeScript the function can't fall off the end. The helper throws, which matters because types disappear at runtime: data from JSON or an older client can still carry a kind the union doesn't list.

assert-never.ts
type Shape =
    | { kind: "circle"; radius: number }
    | { kind: "square"; side: number }
    | { kind: "rect"; width: number; height: number };

// Only a value of type never can be passed in, so every call site
// is a compile-time proof that nothing is left over.
function assertNever(value: never): never {
    throw new Error(`Unhandled 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 "rect":
            return shape.width * shape.height;
        default:
            // Every kind is handled, so shape is narrowed to never here
            return assertNever(shape);
    }
}

const shapes: Shape[] = [
    { kind: "circle", radius: 1 },
    { kind: "square", side: 3 },
    { kind: "rect", width: 2, height: 5 },
];
for (const s of shapes) {
    console.log(s.kind, area(s).toFixed(2));
}

// Types vanish at runtime: data from JSON can still hold a kind the
// union does not know, and assertNever turns it into a clear error.
const fromApi = JSON.parse('{"kind": "hexagon", "side": 2}') as Shape;
try {
    area(fromApi);
} catch (err) {
    console.log((err as Error).message);
}

Output

The three known shapes print circle 3.14, square 9.00 and rect 10.00. The hexagon from the JSON compiles fine, because the as Shape cast tells the checker to trust it, and at runtime it reaches the default case and prints Unhandled value: {"kind":"hexagon","side":2} instead of a silent undefined or NaN. To reject bad data where it enters instead of deep inside a switch, validate it with a type guard (see parse JSON into a typed object).

2What a missing case looks like

Here is the point of the helper. The union below gained a triangle member, and area wasn't updated. After the two cases, the type left in the default branch is the triangle, not never, so the call to assertNever no longer type-checks. This embed fails on purpose: the type error stops the run before anything executes.

missing-case.ts
type Shape =
    | { kind: "circle"; radius: number }
    | { kind: "square"; side: number }
    | { kind: "triangle"; base: number; height: number }; // new member

function assertNever(value: never): never {
    throw new Error(`Unhandled 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;
        // No case for "triangle" yet, so shape is not never in the default
        default:
            return assertNever(shape);
    }
}

console.log(area({ kind: "square", side: 3 }));

Output

The compiler reports error TS2345: Argument of type '{ kind: "triangle"; base: number; height: number; }' is not assignable to parameter of type 'never'. The message names the leftover type, so it doubles as a to-do list: when two members are missing, both appear in it as a union. The check runs at every call to assertNever, so a union used in ten switches fails in all ten places at once. Add the case "triangle": branch and the error goes away.

3Without a helper: const never and satisfies never

If you don't want a shared helper, assign the value to a variable typed never; the assignment is the check. The older answers on Stack Overflow name it _exhaustiveCheck. Since TypeScript 4.9 there is a shorter form: value satisfies never checks the type in place and evaluates to the value itself, so it fits straight into the error message. Both need a statement that ends the default case, here a throw. The { } around the first default gives its const its own block scope.

no-helper.ts
type Status = "draft" | "review" | "published";

// 1. A never-typed variable: the assignment is the check
function label(status: Status): string {
    switch (status) {
        case "draft":
            return "Draft";
        case "review":
            return "In review";
        case "published":
            return "Live";
        default: {
            const unreachable: never = status;
            throw new Error(`Unknown status: ${unreachable}`);
        }
    }
}

// 2. satisfies never (TypeScript 4.9+): checks inline, keeps the value
function color(status: Status): string {
    switch (status) {
        case "draft":
            return "grey";
        case "review":
            return "amber";
        case "published":
            return "green";
        default:
            throw new Error(`Unknown status: ${status satisfies never}`);
    }
}

for (const s of ["draft", "review", "published"] as const) {
    console.log(`${s}: ${label(s)}, ${color(s)}`);
}

try {
    color("deleted" as Status);
} catch (err) {
    console.log((err as Error).message);
}

Output

The three statuses print draft: Draft, grey, review: In review, amber and published: Live, green, and the unknown one throws Unknown status: deleted. The errors differ when a case is missing. Delete the "published" case from label and the assignment fails with error TS2322: Type '"published"' is not assignable to type 'never'.; delete it from color and you get error TS1360: Type '"published"' does not satisfy the expected type 'never'. Both name the missing member, like assertNever does.

4No default at all: the return type check

A switch that returns from every case can skip the default. TypeScript works out that the end of the function is unreachable when every member has a case, and the declared return type does the rest. Remove a case and, with strictNullChecks on (part of strict, as in most projects), the compiler reports error TS2366: Function lacks ending return statement and return type does not include 'undefined'. This page's compiler runs without strict, so here the same missing case compiles with no error at all. That is the first catch of this approach: it depends on a compiler option, and it only works in functions that return a value.

return-type.ts
type Status = "draft" | "review" | "published";

// No default case. With strictNullChecks on, the return type is the
// check: every path must return a string, and TypeScript knows the
// switch covers every Status, so the end of the function is unreachable.
function label(status: Status): string {
    switch (status) {
        case "draft":
            return "Draft";
        case "review":
            return "In review";
        case "published":
            return "Live";
    }
}

console.log(label("review"));

// But nothing guards the runtime: an unknown value falls out of the
// switch and the function quietly returns undefined.
const fromApi = JSON.parse('"deleted"') as Status;
console.log(label(fromApi));
console.log(typeof label(fromApi));

Output

The known status prints In review. The second catch is the runtime: the value from JSON matches no case, falls out of the switch and the function returns undefined, printed twice here, once as the value and once by typeof, even though its type says string. Nothing fails until something later uses that string. The error message also points at the function's return type rather than naming the missing member. Add an assertNever default when the values can come from outside your code.

5A Record map instead of a switch

When every case just picks a value or a function, an object typed Record<Status, string> replaces the switch and is exhaustive by construction: the type requires exactly one property per member of the union. Leaving one out is an error, and so is a key that isn't a member (TS2353), so a typo or a removed member shows up in the map the way a misspelled case does in a switch (TS2678). If the union comes from an array of strings, see create a union type from an array.

record-map.ts
type Status = "draft" | "review" | "published";

// Record<Status, string> needs one key per member: leave one out
// and the object literal fails to compile, add an extra one and it
// fails too.
const labels: Record<Status, string> = {
    draft: "Draft",
    review: "In review",
    published: "Live",
};

// Handlers work the same way: one function per member
const next: Record<Status, (s: Status) => Status> = {
    draft: () => "review",
    review: () => "published",
    published: (s) => s,
};

let status: Status = "draft";
for (let step = 0; step < 3; step++) {
    console.log(`${status} -> ${labels[status]}`);
    status = next[status](status);
}

// A lookup never throws: an unknown key just gives undefined
console.log(labels["deleted" as Status] ?? "(no label)");

Output

The loop prints draft -> Draft, review -> In review and published -> Live, and the unknown key prints (no label). Drop the published line and the build fails with error TS2741: Property 'published' is missing in type '{ draft: string; review: string; }' but required in type 'Record<Status, string>'. Add a deleted key and it fails with error TS2353: Object literal may only specify known properties, and 'deleted' does not exist in type 'Record<Status, string>'. The trade-off is the runtime: a lookup never throws, it returns undefined for an unknown key, hence the ?? fallback.

6Enums, if/else chains and destructured kinds

The check isn't tied to switch or to string unions. An enum is a union of its members, numeric or string, so each case Direction.Up: narrows it the same way. An if/else if chain narrows like a switch, so the final else sees never. And after const { kind } = shape, a switch on kind narrows that variable, so pass kind itself to the helper. For listing an enum's members instead of switching on them, see loop through an enum.

enum-and-if.ts
function assertNever(value: never): never {
    throw new Error(`Unhandled value: ${JSON.stringify(value)}`);
}

// Enums: each member is a case, numeric or string
enum Direction {
    Up,
    Down,
    Left,
    Right,
}

function arrow(d: Direction): string {
    switch (d) {
        case Direction.Up:
            return "↑";
        case Direction.Down:
            return "↓";
        case Direction.Left:
            return "←";
        case Direction.Right:
            return "→";
        default:
            return assertNever(d);
    }
}

// if/else chains narrow the same way, so the final else gets never
type Result =
    | { ok: true; value: number }
    | { ok: false; error: string };

function describe(r: Result): string {
    if (r.ok === true) {
        return `value ${r.value}`;
    } else if (r.ok === false) {
        return `error ${r.error}`;
    } else {
        return assertNever(r);
    }
}

// A destructured kind narrows too: pass kind itself to assertNever
function size(shape: { kind: "s"; n: number } | { kind: "m"; n: number }): string {
    const { kind } = shape;
    switch (kind) {
        case "s":
            return "small";
        case "m":
            return "medium";
        default:
            return assertNever(kind);
    }
}

console.log([Direction.Up, Direction.Left, Direction.Right].map(arrow).join(" "));
console.log(describe({ ok: true, value: 42 }), "|", describe({ ok: false, error: "timeout" }));
console.log(size({ kind: "m", n: 2 }));

Output

It prints ↑ ← →, then value 42 | error timeout, then medium. Note the r.ok === true comparisons. With strictNullChecks on, a plain if (r.ok) narrows a boolean discriminant too. Without it, as on this page's compiler, truthiness doesn't narrow the union: if (r.ok) leaves r as the whole Result, the build fails with error TS2339: Property 'error' does not exist on type 'Result'. and the assertNever call gets a TS2345. Comparing with === works either way.

7Which should you use?

MethodNames the missing caseUnknown value at runtimeBest for
default: return assertNever(x)YesThrowsMost switches: the default
x satisfies neverYesWhatever you write (throw)No helper, TypeScript 4.9+
const _: never = xYesWhatever you write (throw)No helper, any TypeScript version
Return type, no defaultNo, and only with strictNullChecksReturns undefinedShort switches that return, strict projects
Record<Union, T>Yes, and rejects extra keysundefinedEach case only picks a value or handler

Frequently asked questions

Why do I get "Argument of type 'string' is not assignable to parameter of type 'never'"?

The value you pass to assertNever was never narrowed to never, and the type in the message tells you what is left. A member such as "published" or { kind: "triangle"; ... } means a case is missing. Plain string means the switched property is typed string instead of a union of literals, for example interface AppEvent { kind: string }: no number of cases can exhaust string, so the check fails even when every value you care about is handled. Type the property as a union such as "click" | "key", or drop the exhaustive check for open-ended values.

What does the never type mean in an exhaustive check?

never is the type with no values. Each case removes its member from the switched value's type, so after the last one nothing is left and TypeScript types the value as never in the default branch. Only never is assignable to never, so passing the value to a never parameter, assigning it to a never variable or writing value satisfies never compiles only when no member is left over.

Can TypeScript check a switch is exhaustive without a default case?

Only through the return type. If every case returns and the function declares a return type without undefined, a missing case gives error TS2366: Function lacks ending return statement and return type does not include 'undefined'. with strictNullChecks on. It does nothing for switches that do not return, and without strictNullChecks it does nothing at all. For a check with no code in the switch, the typescript-eslint rule @typescript-eslint/switch-exhaustiveness-check reports missing cases from the linter.

Should the default case throw or return a fallback?

Throw when an unknown value is a bug, which is the usual case: assertNever turns it into an error that names the value, as in Unhandled value: {"kind":"hexagon","side":2}. When the value comes from a server that may add members before your client is updated, keep the compile-time check and return a fallback instead: const unhandled: never = value; followed by return "unknown"; still fails the build on a missing case but lets old clients carry on.

Does an exhaustive switch work with enums?

Yes, for numeric and string enums alike: an enum type is the union of its members, so after case Direction.Up: through case Direction.Right: the value is never in the default and assertNever(d) compiles. Add a member to the enum and every switch that uses the check fails until it gets a case.

Is assertNever built into TypeScript?

No. It is a two-line function you write once and import where needed: function assertNever(value: never): never { throw new Error(...) }. The name is just a widespread convention. If you prefer no helper, value satisfies never (TypeScript 4.9+) or const _: never = value give the same compile-time check inline.

Run it yourself

Open any of these in the full TypeScript editor to tweak, run and share.

TypeScript playground