TS-Pattern: The Exhaustive Pattern Matching Library for TypeScript
If you've ever wished TypeScript had pattern matching like Rust or Haskell, your prayers have been answered. TS-Pattern brings exhaustive pattern matching to TypeScript with killer type inference that just gets what you're trying to do.
What It Does
TS-Pattern is a library that lets you write expressive pattern matching expressions in TypeScript. Instead of nested if/else or switch statements, you can declaratively match against patterns and let the library handle the branching logic. The killer feature? It's exhaustive – the compiler will warn you if you've missed any cases.
import { match, P } from 'ts-pattern';
type Response =
| { status: 'success', data: string }
| { status: 'error', error: Error };
const handleResponse = (response: Response) =>
match(response)
.with({ status: 'success' }, ({ data }) => `Got data: ${data}`)
.with({ status: 'error' }, ({ error }) => `Oops: ${error.message}`)
.exhaustive(); // ← Compiler checks all cases are handled
Why It's Cool
-
Type Inference Magic: The library deeply understands your types and narrows them automatically in each branch. No more manual type guards.
-
Expressive Patterns: Match against objects, arrays, primitives, or even custom predicates with a clean syntax.
-
Exhaustiveness Checking: The
.exhaustive()method ensures you've covered all possible cases – no more sneaky runtime errors. -
Functional-Friendly: Works great with Option/Result types and other FP patterns, but stays pragmatic for everyday TypeScript.
-
Tiny & Fast: Zero dependencies and optimized for performance.
How to Try It
Getting started is straightforward:
npm install ts-pattern
Then check out the interactive examples to see the patterns in action. The library works with any TypeScript project and has excellent docs showing all the pattern variations you can use.
Final Thoughts
As someone who's written one too many switch statements with manual type narrowing, TS-Pattern feels like cheating. It makes complex conditional logic declarative and type-safe. The API is intuitive enough that you'll be productive immediately, but powerful enough to handle deep pattern matching scenarios.
If you're working with discriminated unions, state machines, or just want cleaner conditional logic, this library deserves a spot in your toolkit. It's one of those rare packages that changes how you write TypeScript.