Last Updated: 3/6/2026
TS-Pattern
The exhaustive Pattern Matching library for TypeScript with smart type inference.
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();About
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.

Animation by @nicoespeon
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 with
.exhaustive(). - Use patterns to validate the shape of your data with
isMatching. - Expressive API, with catch-all and type specific wildcards:
P._,P.string,P.number, etc. - 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).
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.
Read the introduction blog post: Bringing Pattern Matching to TypeScript 🎨 Introducing TS-Pattern
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-pattern