TypeScript discriminated unions and exhaustive checks, with a real compiler error

Abstract

Model loading, success and error states so impossible combinations cannot compile, and make the compiler tell you when a new case is unhandled.

A common bug in UI and API code is a bundle of loosely related fields: isLoading, error, data. Nothing stops isLoading and error both being set. A discriminated union removes that whole class of bug by making each state its own shape. This tutorial builds one and then shows the compiler catching a forgotten case.

The code was type-checked with TypeScript 7.0.2 in strict mode and run on Node 24. The compiler error shown at the end is real output.

The problem with flags

type Bad = { isLoading: boolean; error?: string; data?: string[] };

This type allows { isLoading: true, error: 'x', data: [] }, a state that means nothing. Every function that uses it has to guess which fields to trust.

The union

type RequestState =
  | { status: 'idle' }
  | { status: 'loading' }
  | { status: 'success'; data: string[] }
  | { status: 'error'; message: string };

Each variant has a status field with a literal type. That field is the discriminant. Only the success variant has data, and only the error variant has message.

Narrowing with a switch

function assertNever(x: never): never {
  throw new Error(`unhandled state: ${JSON.stringify(x)}`);
}

export function describe(state: RequestState): string {
  switch (state.status) {
    case 'idle': return 'Nothing yet';
    case 'loading': return 'Loading...';
    case 'success': return `${state.data.length} items`;
    case 'error': return `Failed: ${state.message}`;
    default: return assertNever(state);
  }
}

Inside case 'success', TypeScript knows state is the success variant, so state.data is allowed. Writing state.data in the error case would be a compile error.

Running describe on one value of each variant prints:

Nothing yet
Loading...
2 items
Failed: timeout

The exhaustiveness trick

After all four cases, nothing is left, so in the default branch state has the type never. The assertNever function accepts only never. If every variant is handled, the call compiles. If one is not, state is something other than never and the call is a type error.

Add a fifth variant without handling it:

type RequestState =
  | { status: 'idle' }
  | { status: 'loading' }
  | { status: 'success'; data: string[] }
  | { status: 'error'; message: string }
  | { status: 'cancelled' };

The compiler responds with:

error TS2345: Argument of type '{ status: "cancelled"; }' is not assignable to parameter of type 'never'.

That message names the missing case. You now have a list of every function that needs updating, produced by the compiler instead of by a bug report. If a never slips through at runtime, assertNever throws with the offending value, which is a better failure than silently returning undefined.

When to use this pattern

  • Request or loading states in a UI.
  • Results where success and failure carry different data, like the Result type in the JSON validation tutorial.
  • Permissions or modes where each mode allows different fields, for instance a payment request that is either proposed or confirmed.

Conclusion

Give each state its own shape, key them with a literal status, and end every switch with assertNever. Adding a state then becomes a compiler-guided edit instead of a hunt.[1]


  1. Reviewer 2 would like a sixth state, “unknown”. The authors have never, which is more honest. ↩︎