Course contentsShow
← TypeScript
Lesson 962 of 1,79622. The never TypeFree lesson

Exhaustiveness in Pattern Matching Libraries

How libraries like ts-pattern use never to enforce exhaustive case coverage.

Exhaustiveness in Pattern Matching Libraries

What you'll learn: How libraries like ts-pattern leverage the never type to enforce compile-time exhaustive case coverage in pattern matching.

The Pattern Matching Problem

Pattern matching libraries (like ts-pattern) provide a cleaner, more expressive alternative to switch statements for handling complex type unions. But they face a challenge: how do you ensure the developer handles every possible case at compile time?

This is where never becomes the enforcement mechanism.

How never Powers Exhaustiveness

When you use a pattern matching library with a discriminated union, the library's generic types progressively narrow what cases remain unhandled. If you call .exhaustive() without covering all cases, the unhandled type gets passed to a function expecting never.

Here's the mental model:

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

// With ts-pattern (conceptual illustration)
match(status)
  .with({ type: 'loading' }, () => 'Loading...')
  .with({ type: 'success' }, (s) => s.data)
  // Missing 'error' case!
  .exhaustive(); // ❌ Compile error: 'error' not assignable to never

The library internally tracks which union members you've matched. The .exhaustive() method expects the remaining unmatched type to be never (meaning nothing left). If cases remain, you get a type error.

Why This Matters

Without this never-based enforcement, you could easily forget to handle a new status type added six months later. The compiler becomes your safety net, catching missing cases before they become runtime bugs.

Key Takeaway: Pattern matching libraries use never as the target type for "all cases handled"—if any union members remain unmatched, they won't assign to never, triggering a compile error that forces exhaustive coverage.