Course contentsShow
← TypeScript
Lesson 420 of 1,7969. Union TypesFree lesson

The never Type in Switch Statements

Using never assignments in default cases to enforce that all union variants are explicitly matched.

The never Type in Switch Statements

You'll learn how to use TypeScript's never type to catch missing cases in switch statements that handle union types.

Why never Makes Switches Bulletproof

When you're switching over a discriminated union, you want to be certain you've handled every possible variant. The never type gives you compile-time proof.

Here's the pattern: add a default case that tries to assign the remaining value to a variable of type never. If you've handled all cases, TypeScript knows nothing reaches the default. If you miss a case, TypeScript will yell at you because you're trying to assign something real to never.

How It Works

type Status = 
  | { kind: 'loading' }
  | { kind: 'success'; data: string }
  | { kind: 'error'; message: string };

function handleStatus(status: Status): string {
  switch (status.kind) {
    case 'loading':
      return 'Loading...';
    case 'success':
      return status.data;
    case 'error':
      return status.message;
    default:
      const exhaustiveCheck: never = status;
      return exhaustiveCheck;
  }
}

If you remove the 'error' case, TypeScript throws an error: "Type 'error' is not assignable to type 'never'". This tells you immediately that you forgot a variant.

Think of It as a Safety Net

The never assignment is like a guard rail that only appears when you take a wrong turn. If all paths are covered, you never reach it. If you miss something, it catches you.

Key Takeaway: Assigning unhandled union variants to never in a default case turns missing switch cases into compile-time errors, ensuring exhaustive coverage.