TypeScript Snippet

Exhaustive assertNever Switch

Difficulty: Easy

Discriminated unions are TypeScript's superpower for state machines, redux reducers, and API response shapes, but a `switch` over them silently goes stale the moment a new variant appears. The `assertNever` helper flips silent staleness into a compile error: any unhandled branch means the type passed in is not actually `never`. This snippet covers the helper, a reducer that uses it for compile-time safety, and an interim `default` strategy for production safety while you iterate.

Code Snippets
/

Exhaustive assertNever Switch

Exhaustive assertNever Switch

Discriminated unions are TypeScript's superpower for state machines, redux reducers, and API response shapes, but a `switch` over them silently goes stale the moment a new variant appears. The `assertNever` helper flips silent staleness into a compile error: any unhandled branch means the type passed in is not actually `never`. This snippet covers the helper, a reducer that uses it for compile-time safety, and an interim `default` strategy for production safety while you iterate.

TypeScript
Easy
3 snippets
ts-type-guards
ts-type-narrowing
ts-conditional-types
code-template

894 views

14

assertNever accepts a value typed as never and throws at runtime. The compile-time win is that, after every other branch narrows away its share of the union, the leftover variable must be never for the call to type-check. Add a third variant to Shape and TypeScript reports an error at the assertNever(shape) line because shape is no longer never there. Throwing in the body keeps runtime behavior loud (instead of silently returning undefined) so the bug surfaces immediately if exhaustiveness was bypassed via as.