On this page

TypeScript Exhaustiveness Checking: Complete Guide

Published on August 1, 2026

Enrico Hochkoeppler Profile

By Enrico Hochkoeppler

Web Developer & TutoriaLibre Founder

Exhaustiveness checking is a TypeScript technique that ensures every possible variant of a discriminated union or enum is handled in a switch statement or conditional logic. By assigning the remaining value to a variable of type never in the default case, TypeScript will raise a compile-time error if a new variant is added but not handled. This pattern turns entire categories of runtime bugs into compile-time errors—when you add a new member to a union, TypeScript forces you to update every place that handles that union. The technique is widely used in real-world applications: from API response handling and Redux reducers to UI state machines and WebSocket request/response infrastructures. Linters such as @typescript-eslint/switch-exhaustiveness-check and Oxc's switch-exhaustiveness-check can enforce this pattern automatically across your codebase.


What Is Exhaustiveness Checking?​

Exhaustiveness checking is a TypeScript feature that guarantees all possible cases of a discriminated union have been handled in a switch statement or conditional logic. When you use a discriminated union — a union of object types that share a common, literal-valued discriminant property — TypeScript can narrow the type within each case of a switch statement. Exhaustiveness checking leverages the never type to enforce that every variant is covered.

The never Type​

The never type represents a value that should never occur. It is assignable to every type, but no type is assignable to never (except never itself). In an exhaustive switch, once the object reaches the default case, its type has been narrowed to never. If a new variant is added to the union and not handled, TypeScript will raise an error on the assignment.


Basic Example: Shape Area Calculator​

Consider a discriminated union representing different shapes:


type Shape = 

    | { kind: 'circle'; radius: number }

    | { kind: 'rectangle'; width: number; height: number };

If you write a function to calculate the area without exhaustiveness checking, TypeScript will allow it even if you forget a case:


function calculateArea(shape: Shape): number {

    switch (shape.kind) {

        case 'circle':

            return Math.PI * shape.radius ** 2;

        case 'rectangle':

            return shape.width * shape.height;

    }

}

This code appears correct, but if you later add a new shape type — say, 'triangle' — you might forget to handle it. TypeScript won't warn you.

Adding Exhaustiveness Checking​

To enforce exhaustiveness, add a default case that assigns the shape to a variable of type never:


function calculateArea(shape: Shape): number {

    switch (shape.kind) {

        case 'circle':

            return Math.PI * shape.radius ** 2;

        case 'rectangle':

            return shape.width * shape.height;

        default:

            const _exhaustiveCheck: never = shape;

            return _exhaustiveCheck;

    }

}

Now, if you add a new shape type — { kind: 'triangle'; base: number; height: number } — TypeScript will raise an error on the line const _exhaustiveCheck: never = shape, alerting you to the missing case. This is TypeScript's way of saying: “You forgot to handle one of the variants.”


Exhaustiveness Checking with Enums​

The same pattern works with enums:


enum Color {

    Red,

    Green,

    Blue,

}



function getColorName(color: Color): string {

    switch (color) {

        case Color.Red:

            return 'red';

        case Color.Green:

            return 'green';

        default:

            const _exhaustiveCheck: never = color;

            return _exhaustiveCheck;

    }

}

If you add a new enum member — Color.Yellow — TypeScript will error because color is no longer assignable to never.


Exhaustiveness Checking Without a switch​

You can also enforce exhaustiveness in if/else chains:


type Result = 

    | { status: 'success'; data: string }

    | { status: 'error'; error: Error }

    | { status: 'loading' };



function handleResult(result: Result): string {

    if (result.status === 'success') {

        return result.data;

    }

    if (result.status === 'error') {

        return result.error.message;

    }

    // Exhaustiveness check

    const _exhaustiveCheck: never = result;

    return _exhaustiveCheck;

}

If you add a new status — say, 'idle' — TypeScript will error on the never assignment.


The assertNever Helper​

To avoid repeating the never assignment pattern, you can create a helper function:


function assertNever(value: never): never {

    throw new Error(`Unhandled discriminated union member: ${value}`);

}

Then use it in the default case:


function calculateArea(shape: Shape): number {

    switch (shape.kind) {

        case 'circle':

            return Math.PI * shape.radius ** 2;

        case 'rectangle':

            return shape.width * shape.height;

        default:

            return assertNever(shape);

    }

}

The assertNever function provides both compile-time safety and runtime protection.


Exhaustiveness Checking with satisfies never​

TypeScript 4.9 introduced the satisfies operator, which can be used for exhaustiveness checking:


function calculateArea(shape: Shape): number {

    switch (shape.kind) {

        case 'circle':

            return Math.PI * shape.radius ** 2;

        case 'rectangle':

            return shape.width * shape.height;

        default:

            throw new Error(`Unhandled shape: ${shape satisfies never}`);

    }

}

This pattern is enforced by some ESLint plugins.


Real-World Example: WebSocket Request/Response​

Discriminated unions and exhaustiveness checking are particularly valuable in API and WebSocket infrastructures:


type RequestA = { action: 'a'; args: { id: number } };

type RequestB = { action: 'b'; args: { name: string } };

type Request = RequestA | RequestB;



type ResponseA = { result: string };

type ResponseB = { result: number };

type Response = ResponseA | ResponseB;



async function handleRequest(request: Request): Promise<Response> {

    switch (request.action) {

        case 'a':

            return { result: `Processed ${request.args.id}` };

        case 'b':

            return { result: request.args.name.length };

        default:

            const _exhaustiveCheck: never = request;

            throw new Error(`Unhandled action: ${_exhaustiveCheck}`);

    }

}

The compiler enforces that every request type is handled and that each returns the correct response type.


Linting with switch-exhaustiveness-check​

The @typescript-eslint/switch-exhaustiveness-check rule enforces exhaustive switch statements:


{

    "rules": {

        "@typescript-eslint/switch-exhaustiveness-check": "error"

    }

}

This rule reports an error when a switch statement over a union of literals or an enum is missing a case for any of those literal types and does not have a default clause. The rule requires type information to run.

Configuration Options​

Oxc provides a similar rule under typescript/switch-exhaustiveness-check.


When to Use Exhaustiveness Checking​


Summary​

Exhaustiveness checking is one of TypeScript's most powerful safety features. It turns runtime bugs into compile-time errors by forcing you to handle every variant of a discriminated union. The technique uses the never type in a default case — or with an assertNever helper — to alert you when a new variant is added without being handled. Linters like @typescript-eslint/switch-exhaustiveness-check can enforce this pattern automatically across your codebase. By adopting exhaustiveness checking, you make refactoring safer, eliminate silent failures, and build more reliable applications.

Frequently Asked Questions​

What is exhaustiveness checking in TypeScript?

Exhaustiveness checking is a technique that ensures every variant of a discriminated union or enum is handled in a switch statement or conditional logic. It uses the `never` type to catch missing cases at compile time, turning potential runtime bugs into compile-time errors.

What is the `never` type and why is it used in exhaustiveness checking?

The `never` type represents a value that should never occur. In exhaustiveness checking, you assign the remaining value in a `default` case to a variable of type `never`. If a new variant is added but not handled, TypeScript raises an error because the value is not assignable to `never`.

How do I implement exhaustiveness checking in a switch statement?

Add a `default` case that assigns the switch subject to a variable of type `never`. For example: `default: const _exhaustiveCheck: never = shape; return _exhaustiveCheck;`. TypeScript will error if any union variant is not handled in the preceding cases.

What happens if I forget the `default` case in a switch over a discriminated union?

If you forget the `default` case, TypeScript will not raise an error when a new variant is added. The function will return `undefined` or continue to the next statement, potentially causing runtime bugs. The `default` case with a `never` assignment enforces completeness.

Does exhaustiveness checking work with enums?

Yes. The same pattern works with enums. Example: `switch (color) { case Color.Red: return 'red'; default: const _exhaustiveCheck: never = color; return _exhaustiveCheck; }`. Adding a new enum member without handling it will cause a compile-time error.

Can I use exhaustiveness checking without a switch statement?

Yes, you can use it in `if`/`else` chains. After handling all known cases, assign the remaining value to `never`. Example: `if (result.status === 'success') { ... } if (result.status === 'error') { ... } const _exhaustiveCheck: never = result; return _exhaustiveCheck;`.

What is the `assertNever` helper and why would I use it?

`assertNever` is a helper function that takes a `never` parameter and throws an error: `function assertNever(value: never): never { throw new Error('Unhandled union member'); }`. It reduces repetition and provides both compile-time safety and runtime protection.

Does the `default` case with `never` cause a runtime error?

No, the `never` assignment only affects compile-time checking. If all variants are handled, the `default` case is never reached at runtime. The `throw` in `assertNever` would only execute if a new, unhandled variant is encountered at runtime.

Why does TypeScript error when I try to assign a union type to `never`?

Because `never` is the type of values that never occur. A union type that has been partially narrowed but still contains unhandled variants is not assignable to `never`. TypeScript is telling you that you have not handled all possible variants.

Does the ESLint rule `switch-exhaustiveness-check` enforce this pattern automatically?

Yes, `@typescript-eslint/switch-exhaustiveness-check` automatically enforces exhaustive `switch` statements. It reports an error when a `switch` statement over a union or enum is missing a case for any of those types and does not have a `default` clause.

What is the `satisfies never` pattern in exhaustiveness checking?

TypeScript 4.9 introduced the `satisfies` operator, which can be used for exhaustiveness checking: `throw new Error('Unhandled: ' + (shape satisfies never));`. The `satisfies never` expression ensures the value is assignable to `never`, raising a compile-time error if it isn't.

Can I use exhaustiveness checking with discriminated unions that have non-literal discriminants?

Exhaustiveness checking works best with literal discriminants because TypeScript can narrow the type precisely. Non-literal discriminants (like `string` or `number`) do not provide the same level of narrowing, so the pattern may not work as expected.

How do I handle exhaustiveness checking in a function that returns different types for each case?

Each `case` must return the same type or a union of types that is compatible with the function's return type. The `default` case with `never` helps ensure all cases are covered, but the return type must be consistent across all branches.

What is the difference between exhaustiveness checking with `never` and using a `default` case with a runtime error?

A `default` case with a runtime error (`throw new Error(...)`) catches missing cases at runtime. A `default` case with a `never` assignment catches missing cases at compile time. The `never` pattern is preferred because it catches bugs before the code runs.

Does exhaustiveness checking work with nested discriminated unions?

Yes, but you need to handle each level of nesting separately. You can use nested `switch` statements or destructure the nested discriminant. Each `switch` should have its own exhaustiveness check.

What happens if I use `as any` or `as never` to bypass the exhaustiveness check?

Using `as any` or `as never` bypasses the type checker and defeats the purpose of exhaustiveness checking. If you use type assertions, TypeScript will not warn you about missing cases. Always use the `never` assignment pattern without type assertions.

Can I use exhaustiveness checking with arrays of discriminated unions?

Yes. You can iterate over an array and handle each element. Within the loop, apply the same `switch` with `never` pattern. However, TypeScript's control flow analysis does not narrow array elements based on the loop context, so you may need to use a type guard inside the loop.

How do I enforce exhaustiveness checking in a large codebase?

Enable the `@typescript-eslint/switch-exhaustiveness-check` rule in your ESLint configuration. This will automatically enforce exhaustiveness for all `switch` statements over unions and enums across your entire codebase.

What is the relationship between exhaustiveness checking and discriminated unions?

Discriminated unions are the foundation of exhaustiveness checking. The shared discriminant property with literal values allows TypeScript to narrow the type in each `case`. Exhaustiveness checking ensures that every variant defined in the discriminated union is handled.

Can I use the `never` pattern in a `switch` with a `default` case that also returns a value?

The `default` case should assign the value to `never` and then either return or throw. If you try to return a value from the `default` case without assigning to `never`, TypeScript may not catch missing cases. Always include the `never` assignment before returning.

Found this helpful? Share the knowledge...

... or support this project to keep it alive!

Buy Me a Coffee

Previous

Custom Type Guards

Next

Hands-On: Build a Safe Parser for External API Data