Last Updated: 3/18/2026
Overview and Installation
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.
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)
Installation
Via npm:
npm install ts-patternYou can also use your favorite package manager:
pnpm add ts-pattern
# OR
yarn add ts-pattern
# OR
bun add ts-pattern
# OR
npx jsr add @gabriel/ts-patternQuick 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();Benefits
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.