Last Updated: 3/6/2026
Introduction to TS-Pattern
TS-Pattern is the exhaustive Pattern Matching library for TypeScript with smart type inference.
What is Pattern Matching?
Pattern Matching is a code-branching technique coming from functional programming languages that’s more powerful and often less verbose than imperative alternatives (if/else/switch statements), especially for complex conditions.
Pattern Matching is implemented in Python, Rust, Swift, Elixir, Haskell and many other languages. There is a tc39 proposal to add Pattern Matching to EcmaScript, but it is still in stage 1 and isn’t likely to land before several years. Luckily, pattern matching can be implemented in userland. ts-pattern Provides a typesafe pattern matching implementation that you can start using today.
Why Use TS-Pattern?
Write better and safer conditions. Pattern matching lets you express complex conditions in a single, compact expression. Your code becomes shorter and more readable. Exhaustiveness checking ensures you haven’t forgotten any possible case.
Quick Example
import { match, P } from 'ts-pattern';
type Data =
| { type: 'text'; content: string }
| { type: 'img'; src: string };
type Result =
| { type: 'ok'; data: Data }
| { type: 'error'; error: Error };
const result: Result = ...;
const html = match(result)
.with({ type: 'error' }, () => <p>Oups! An error occured</p>)
.with({ type: 'ok', data: { type: 'text' } }, (res) => <p>{res.data.content}</p>)
.with({ type: 'ok', data: { type: 'img', src: P.select() } }, (src) => <img src={src} />)
.exhaustive();Key Features
- Pattern-match on any data structure: nested Objects, Arrays, Tuples, Sets, Maps and all primitive types
- Typesafe, with helpful type inference
- Exhaustiveness checking support, enforcing that you are matching every possible case
- Use patterns to validate the shape of your data with
isMatching - Expressive API, with catch-all and type specific wildcards
- Supports predicates, unions, intersections and exclusion patterns for non-trivial cases
- Supports properties selection, via the
P.select(name?)function - Tiny bundle footprint (only ~2kB)
Read the introduction blog post: Bringing Pattern Matching to TypeScript 🎨 Introducing TS-Pattern