Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
T

ts-pattern

> 编程语言
Open source

🎨 The exhaustive Pattern Matching library for TypeScript, with smart type inference.

15.1K stars0 likes3 views
WebsiteGitHub

About

🎨 The exhaustive Pattern Matching library for TypeScript, with smart type inference.

TS-Pattern

The exhaustive Pattern Matching library for TypeScript with smart type inference.

typescript
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) => )
  .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

bash
npm install ts-pattern

You can also use your favorite package manager:

bash
pnpm add ts-pattern
# OR
yarn add ts-pattern
# OR
bun add ts-pattern
# OR
npx jsr add @gabriel/ts-pattern

Want to become a TypeScript Expert?

Check out 👉 Type-Level TypeScript, an online course teaching you how to unleash the full potential of TypeScript's Turing-complete type system. You already know how to code, and types are simply another programming language to master. This course bridges the gap, helping you apply your existing programming knowledge to TypeScript's type system, so you never again struggle with type errors or feel unable to type complex generic code correctly!

Documentation

  • Sandbox examples
  • Getting Started
  • API Reference
    • match
    • .with
    • .when
    • .returnType
    • .exhaustive
    • .otherwise
    • .narrow
    • isMatching
    • Patterns
      • Literals
      • Wildcards
      • Objects
      • Tuples (arrays)
      • P.array patterns
      • P.record patterns
      • P.set
      • P.map
      • P.when patterns
      • P.not patterns
      • P.select patterns
      • P.optional patterns
      • P.instanceOf patterns
      • P.union patterns
      • P.intersection patterns
      • P.string predicates
      • P.number and P.bigint predicates
    • Types
      • P.infer
      • P.Pattern
      • Type inference
  • Inspirations

Sandbox examples

  • Basic Demo
  • React gif fetcher app Demo
  • React.useReducer Demo
  • Handling untyped API response Demo
  • P.when Guard Demo
  • P.not Pattern Demo
  • P.select Pattern Demo
  • P.union Pattern Demo

Getting Started

As an example, let's create a state reducer for a frontend application that fetches some data.

Example: a state reducer with ts-pattern

Our application can be in four different states: idle, loading, success and error. Depending on which state we are in, some events can occur. Here are all the possible types of event our application can respond to: fetch, success, error and cancel.

I use the word event but you can replace it with action if you are used to Redux's terminology.

typescript
type State =
  | { status: 'idle' }
  | { status: 'loading'; startTime: number }
  | { status: 'success'; data: string }
  | { status: 'error'; error: Error };

type Event =
  | { type: 'fetch' }
  | { type: 'success'; data: string }
  | { type: 'error'; error: Error }
  | { type: 'cancel' };

Even though our application can handle 4 events, only a subset of these events make sense for each given state. For instance we can only cancel a request if we are currently in the loading state. To avoid unwanted state changes that could lead to bugs, we want our state reducer function to branch on both the state and the event, and return a new state.

This is a case where match really shines. Instead of writing nested switch statements, we can use pattern matching to simultaneously check the state and the event object:

…

There's a lot going on, so let's go through this code bit by bit:

match(value)

match takes a value and returns a builder on which you can add your pattern matching cases.

typescript
match([state, event])

It's also possible to specify the input and output type explicitly with match<Input, Output>(...), but this is usually unnecessary, as TS-Pattern is able to infer them.

.returnType<OutputType>()

.returnType is an optional method that you can call if you want to force all following code-branches to return a value of a specific type. It takes a single type parameter, provided between <AngleBrackets>.

typescript
  .returnType<State>()

Here, we use this method to make sure all branches return a valid State object.

.with(pattern, handler)

Then we add a first with clause:

typescript
  .with(
    [{ status: 'loading' }, { type: 'success' }],
    ([state, event]) => ({
      // `state` is inferred as { status: 'loading' }
      // `event` is inferred as { type: 'success', data: string }
      status: 'success',
      data: event.data,
    })
  )

The first argument is the pattern: the shape of value you expect for this branch.

The second argument is the handler function: the code branch that will be called if the input value matches the pattern.

The handler function takes the input value as first parameter with its type narrowed down to what the pattern matches.

P.select(name?)

In the second with clause, we use the P.select function:

typescript
  .with(
    [
      { status: 'loading' },
      { type: 'error', error: P.select() }
    ],
    (error) => ({ status: 'error', error })
  )

P.select() lets you extract a piece of your input value and inject it into your handler. It is pretty useful when pattern matching on deep data structures because it avoids the hassle of destructuring your input in your handler.

Since we didn't pass any name to P.select(), It will inject the event.error property as first argument to the handler function. Note that you can still access the full input value with its type narrowed by your pattern as second argument of the handler function:

typescript
  .with(
    [
      { status: 'loading' },
      { type: 'error', error: P.select() }
    ],
    (error, stateAndEvent) => {
      // error: Error
      // stateAndEvent: [{ status: 'loading' }, { type: 'error', error: Error }]
    }
  )

In a pattern, we can only have a single anonymous selection. If you need to select more properties on your input data structure, you will need to give them names:

typescript
.with(
    [
      { status: 'success', data: P.select('prevData') },
      { type: 'error', error: P.select('err') }
    ],
    ({ prevData, err }) => {
      // Do something with (prevData: string) and (err: Error).
    }
  )

Each named selection will be injected inside a selections object, passed as first argument to the handler function. Names can be any strings.

P.not(pattern)

If you need to match on everything but a specific value, you can use a P.not(<pattern>) pattern. it's a function taking a pattern and returning its opposite:

typescript
  .with(
    [{ status: P.not('loading') }, { type: 'fetch' }],
    () => ({ status: 'loading' })
  )

P.when() and guard functions

Sometimes, we need to make sure our input value respects a condition that can't be expressed by a pattern. For example, imagine you need to check that a number is positive. In these cases, we can use guard functions: functions taking a value and returning a boolean.

With TS-Pattern, there are two ways to use a guard function:

  • use P.when(<guard function>) inside one of your patterns
  • pass it as second parameter to .with(...)

using P.when(predicate)

typescript
  .with(
    [
      {
        status: 'loading',
        startTime: P.when((t) => t + 2000 < Date.now()),
      },
      { type: 'cancel' },
    ],
    () => ({ status: 'idle' })
  )

Passing a guard function to .with(...)

.with optionally accepts a guard function as second parameter, between the pattern and the handler callback:

typescript
  .with(
    [{ status: 'loading' }, { type: 'cancel' }],
    ([state, event]) => state.startTime + 2000 < Date.now(),
    () => ({ status: 'idle' })
  )

This

Issues· 77 open

View all issuesOpen on GitHub
  • #335

    Incorrect array exhaustiveness check

    Updated Sep 30, 2026
  • #360

    Build fails on main after picomatch 2.3.2 upgrade

    Updated Aug 5, 2026
  • #354

    Nullable NoInfer breaks `with()` handler

    Updated Jun 10, 2026
  • #183

    `exhaustive` doesn't work when the conditions use an enum with numeric values

    Updated Dec 14, 2025
  • #340

    patterns of type `P.Pattern` do not work

    Updated Dec 12, 2025
  • #323

    Branded type does not work anymore

    Updated Dec 4, 2025
  • #334

    const/literal handlers

    enhancementUpdated Nov 17, 2025
  • #336

    `P.instanceOf(Text)` not working with `isMatching`

    Updated Oct 30, 2025
  • #333

    P.when behaves incorrectly in corner cases when types have intersection

    Updated Sep 25, 2025
  • #331

    P.select loses type inference when used with multiple patterns in a single .with

    Updated Sep 15, 2025

> Tags

TypeScriptbranchingconditionsexhaustiveinference

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedOct 1, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言