ts-pattern

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

README

TS-Pattern

The exhaustive Pattern Matching library for TypeScript

with smart type inference.

downloads npm version MIT license


  1. ```ts
  2. import { match, P } from 'ts-pattern';

  3. type Data =
  4.   | { type: 'text'; content: string }
  5.   | { type: 'img'; src: string };

  6. type Result =
  7.   | { type: 'ok'; data: Data }
  8.   | { type: 'error'; error: Error };

  9. const result: Result = ...;

  10. return match(result)
  11.   .with({ type: 'error' }, () => `<p>Oups! An error occured</p>`)
  12.   .with({ type: 'ok', data: { type: 'text' } }, (res) => `<p>${res.data.content}</p>`)
  13.   .with({ type: 'ok', data: { type: 'img', src: P.select() } }, (src) => `<img src=${src} />`)
  14.   .exhaustive();
  15. ```

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.

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()](#exhaustive).
- Use patterns tovalidate the shape of your data with [isMatching](#ismatching).
- Expressive API, with catch-all and type specific wildcards: [P._](#P_-wildcard), [P.string](#Pstring-wildcard), [P.number](#Pnumber-wildcard), etc.
- Supports [predicates](#Pwhen-patterns), [unions](#Punion-patterns), [intersections](#Pintersection-patterns) and [exclusion](#Pnot-patterns) patterns for non-trivial cases.
- Supports properties selection, via the [P.select(name?)](#Pselect-patterns) function.
- Tiny bundle footprint ([only 1.7kB](https://bundlephobia.com/package/ts-pattern)).

What is Pattern Matching?


Pattern Matching is a code-branching technique coming from functional programming languages, which lets you scrutinize the structure of values in a declarative way. It has proven itself to be less verbose and more powerful than imperative alternatives (if/else/switch statements), especially when branching on complex data structures or on several values.

Pattern Matching is implemented in Haskell, Rust, Swift, Elixir and many other languages. There is a tc39 proposal to add Pattern Matching to the EcmaScript specification, 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.


Installation


Via npm

  1. ```
  2. npm install ts-pattern
  3. ```

Via yarn

  1. ```
  2. yarn add ts-pattern
  3. ```

Compatibility with different TypeScript versions


Note: TS-Pattern assumes Strict Mode is enabled in yourtsconfig.json file.

ts-patternTypeScriptTypeScriptTypeScript
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
v4.x
v3.x⚠️
v2.x

- ✅ Full support
- ⚠️ Partial support, All features except passing multiple patterns to .with().
- ❌ Not supported

Documentation


  - [match](#match)
  - [.with](#with)
  - [.when](#when)
  - [.exhaustive](#exhaustive)
  - [.otherwise](#otherwise)
  - [.run](#run)
  - [isMatching](#ismatching)
  - Patterns
    - Literals
    - Wildcards
    - Objects
    - Tuples (arrays)
    - Sets
    - Maps
    - [P.array patterns](#Parray-patterns)
    - [P.when patterns](#Pwhen-patterns)
    - [P.not patterns](#Pnot-patterns)
    - [P.select patterns](#Pselect-patterns)
    - [P.optional patterns](#Poptional-patterns)
    - [P.instanceOf patterns](#Pinstanceof-patterns)
    - [P.union patterns](#Punion-patterns)
    - [P.intersection patterns](#Pintersection-patterns)
  - Types
    - [P.infer](#Pinfer)
    - [P.Pattern](#PPattern)
    - Type inference

Code Sandbox Examples


- [P.when Guard Demo](https://codesandbox.io/s/ts-pattern-examples-v4-bdy5p2?file=/src/examples/when.tsx)
- [P.not Pattern Demo](https://codesandbox.io/s/ts-pattern-examples-v4-bdy5p2?file=/src/examples/not.tsx)
- [P.select Pattern Demo](https://codesandbox.io/s/ts-pattern-examples-v4-bdy5p2?file=/src/examples/select.tsx)
- [P.union Pattern Demo](https://codesandbox.io/s/ts-pattern-examples-v4-bdy5p2?file=/src/examples/union.tsx)

Getting Started


As an example, we are going to create a state reducer for a
frontend application fetching some data using an HTTP request.

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.

  1. ```ts
  2. type State =
  3.   | { status: 'idle' }
  4.   | { status: 'loading'; startTime: number }
  5.   | { status: 'success'; data: string }
  6.   | { status: 'error'; error: Error };

  7. type Event =
  8.   | { type: 'fetch' }
  9.   | { type: 'success'; data: string }
  10.   | { type: 'error'; error: Error }
  11.   | { type: 'cancel' };
  12. ```

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 to create
a reducer function that matches 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 do that in a very expressive way:


  1. ```ts
  2. import { match, P } from 'ts-pattern';

  3. const reducer = (state: State, event: Event): State =>
  4.   match<[State, Event], State>([state, event])
  5.     .with(
  6.       [{ status: 'loading' }, { type: 'success' }],
  7.       ([, event]) => ({
  8.         status: 'success',
  9.         data: event.data,
  10.       })
  11.     )
  12.     .with(
  13.       [{ status: 'loading' }, { type: 'error', error: P.select() }],
  14.       (error) => ({
  15.         status: 'error',
  16.         error,
  17.       })
  18.     )
  19.     .with(
  20.       [{ status: P.not('loading') }, { type: 'fetch' }],
  21.       () => ({
  22.         status: 'loading',
  23.         startTime: Date.now(),
  24.       })
  25.     )
  26.     .with(
  27.       [
  28.         {
  29.           status: 'loading',
  30.           startTime: P.when((t) => t + 2000 < Date.now()),
  31.         },
  32.         { type: 'cancel' },
  33.       ],
  34.       () => ({
  35.         status: 'idle',
  36.       })
  37.     )
  38.     .with(P._, () => state)
  39.     .exhaustive();
  40. ```

Let's go through this bit by bit:

match(value)


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

  1. ```ts
  2. match<[State, Event], State>([state, event]);
  3. ```

Here we wrap the state and the event objects in an array and we explicitly
specify the type [State, Event] to make sure it is interpreted as
a Tuple by TypeScript, so we
can match on each value separately.

Most of the time, you don't need to specify the type of input
and output with `match(...)` because `match` is able to
infer both of these types.

.with(pattern, handler)


Then we add a first with clause:

  1. ```ts
  2.   .with(
  3.     [{ status: 'loading' }, { type: 'success' }],
  4.     ([state, event]) => ({
  5.       // `state` is inferred as { status: 'loading' }
  6.       // `event` is inferred as { type: 'success', data: string }
  7.       status: 'success',
  8.       data: event.data,
  9.     })
  10.   )
  11. ```

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:

  1. ```ts
  2.   .with(
  3.     [
  4.       { status: 'loading' },
  5.       { type: 'error', error: P.select() }
  6.     ],
  7.     (error) => ({
  8.       status: 'error',
  9.       error,
  10.     })
  11.   )
  12. ```

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:

  1. ```ts
  2.   .with(
  3.     [
  4.       { status: 'loading' },
  5.       { type: 'error', error: P.select() }
  6.     ],
  7.     (error, stateAndEvent) => {
  8.       // error: Error
  9.       // stateAndEvent: [{ status: 'loading' }, { type: 'error', error: Error }]
  10.     }
  11.   )
  12. ```

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:

  1. ```ts
  2. .with(
  3.     [
  4.       { status: 'success', data: P.select('prevData') },
  5.       { type: 'error', error: P.select('err') }
  6.     ],
  7.     ({ prevData, err }) => {
  8.       // Do something with (prevData: string) and (err: Error).
  9.     }
  10.   )
  11. ```

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. it's a function taking a pattern and returning its opposite:

  1. ```ts
  2.   .with(
  3.     [{ status: P.not('loading') }, { type: 'fetch' }],
  4.     () => ({
  5.       status: 'loading',
  6.     })
  7.   )
  8. ```

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 if 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 options to use a guard function:

- use `P.when()` inside your pattern
- pass it as second parameter to .with(...)

using P.when(predicate)


  1. ```ts
  2.   .with(
  3.     [
  4.       {
  5.         status: 'loading',
  6.         startTime: P.when((t) => t + 2000 < Date.now()),
  7.       },
  8.       { type: 'cancel' },
  9.     ],
  10.     () => ({
  11.       status: 'idle',
  12.     })
  13.   )
  14. ```

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


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

  1. ```ts
  2.   .with(
  3.     [{ status: 'loading' }, { type: 'cancel' }],
  4.     ([state, event]) => state.startTime + 2000 < Date.now(),
  5.     () => ({
  6.       status: 'idle'
  7.     })
  8.   )
  9. ```

This pattern will only match if the guard function returns true.

the P._ wildcard


P._ will match any value. You can use it either at the top level, or within another pattern.

  1. ```ts
  2.   .with(P._, () => state)

  3.   // You could also use it inside another pattern:
  4.   .with([P._, P._], () => state)

  5.   // at any level:
  6.   .with([P._, { type: P._ }], () => state)

  7. ```

.exhaustive(), .otherwise() and .run()


  1. ```ts
  2.   .exhaustive();
  3. ```

.exhaustive() executes the pattern matching expression, and returns the result. It also enables exhaustiveness checking, making sure we don't forget any possible case in our input value. This extra type safety is very nice because forgetting a case is an easy mistake to make, especially in an evolving code-base.

Note that exhaustive pattern matching is optional. It comes with the trade-off of having longer compilation times because the type checker has more work to do.

Alternatively you can use .otherwise(), which takes an handler function returning a default value. .otherwise(handler) is equivalent to .with(P._, handler).exhaustive().

  1. ```ts
  2.   .otherwise(() => state);
  3. ```

If you don't want to use .exhaustive() and also don't want to provide a default value with .otherwise(), you can use .run() instead:

  1. ```ts
  2.   .run();
  3. ```

It's just like .exhaustive(), but it's unsafe and might throw runtime error if no branch matches your input value.

Matching several patterns


As you may know, switch statements allow handling several cases with
the same code block:

  1. ```ts
  2. switch (type) {
  3.   case 'text':
  4.   case 'span':
  5.   case 'p':
  6.     return 'text';

  7.   case 'btn':
  8.   case 'button':
  9.     return 'button';
  10. }
  11. ```

Similarly, ts-pattern lets you pass several patterns to .with() and if
one of these patterns matches your input, the handler function will be called:

  1. ```ts
  2. const sanitize = (name: string) =>
  3.   match(name)
  4.     .with('text', 'span', 'p', () => 'text')
  5.     .with('btn', 'button', () => 'button')
  6.     .otherwise(() => name);

  7. sanitize('span'); // 'text'
  8. sanitize('p'); // 'text'
  9. sanitize('button'); // 'button'
  10. ```

As you might expect, this also works with more complex patterns than strings and exhaustiveness checking works as well.

API Reference


match


  1. ```ts
  2. match(value);
  3. ```

Create a Match object on which you can later call .with, .when, .otherwise and .run.

Signature


  1. ```ts
  2. function match<TInput, TOutput>(input: TInput): Match<TInput, TOutput>;
  3. ```

Arguments


- input
  - Required
  - the input value your patterns will be tested against.

.with


  1. ```ts
  2. match(...)
  3.   .with(pattern, [...patterns], handler)
  4. ```

Signature


  1. ```ts
  2. function with(
  3.   pattern: Pattern<TInput>,
  4.   handler: (selections: Selections<TInput>, value: TInput) => TOutput
  5. ): Match<TInput, TOutput>;

  6. // Overload for multiple patterns
  7. function with(
  8.   pattern1: Pattern<TInput>,
  9.   ...patterns: Pattern<TInput>[],
  10.   // no selection object is provided when using multiple patterns
  11.   handler: (value: TInput) => TOutput
  12. ): Match<TInput, TOutput>;

  13. // Overload for guard functions
  14. function with(
  15.   pattern: Pattern<TInput>,
  16.   when: (value: TInput) => unknown,
  17.   handler: (
  18.     selection: Selection<TInput>,
  19.     value: TInput
  20.   ) => TOutput
  21. ): Match<TInput, TOutput>;
  22. ```

Arguments


- `pattern: Pattern`
  - Required
  - The pattern your input must match for the handler to be called.
  - If you provide several patterns before providing the handler, the with clause will match if one of the patterns matches.
- when: (value: TInput) => unknown
  - Optional
  - Additional condition the input must satisfy for the handler to be called.
  - The input will match if your guard function returns a truthy value.
  - TInput might be narrowed to a more precise type using the pattern.
- `handler: (value: TInput, selections: Selections) => TOutput`
  - Required
  - Function called when the match conditions are satisfied.
  - All handlers on a single match case must return values of the same type, TOutput.
  - TInput might be narrowed to a more precise type using the pattern.
  - selections is an object of properties selected from the input with the [select function](#select-patterns).

.when


  1. ```ts
  2. match(...)
  3.   .when(predicate, handler)
  4. ```

Signature


  1. ```ts
  2. function when(
  3.   predicate: (value: TInput) => unknown,
  4.   handler: (value: TInput) => TOutput
  5. ): Match<TInput, TOutput>;
  6. ```

Arguments


- predicate: (value: TInput) => unknown
  - Required
  - Condition the input must satisfy for the handler to be called.
- handler: (value: TInput) => TOutput
  - Required
  - Function called when the predicate condition is satisfied.
  - All handlers on a single match case must return values of the same type, TOutput.

.exhaustive


  1. ```ts
  2. match(...)
  3.   .with(...)
  4.   .exhaustive()
  5. ```

Runs the pattern-matching expression and returns its result. It also enables exhaustiveness checking, making sure at compile time that we have handled all possible cases.

Signature


  1. ```ts
  2. function exhaustive(): IOutput;
  3. ```

Example


  1. ```ts
  2. type Permission = 'editor' | 'viewer';
  3. type Plan = 'basic' | 'pro';

  4. const fn = (org: Plan, user: Permission) =>
  5.   match([org, user] as const)
  6.     .with(['basic', 'viewer'], () => {})
  7.     .with(['basic', 'editor'], () => {})
  8.     .with(['pro', 'viewer'], () => {})
  9.     // Fails with `NonExhaustiveError<['pro', 'editor']>`
  10.     // because the `['pro', 'editor']` case isn't handled.
  11.     .exhaustive();

  12. const fn2 = (org: Plan, user: Permission) =>
  13.   match([org, user] as const)
  14.     .with(['basic', 'viewer'], () => {})
  15.     .with(['basic', 'editor'], () => {})
  16.     .with(['pro', 'viewer'], () => {})
  17.     .with(['pro', 'editor'], () => {})
  18.     .exhaustive(); // Works!
  19. ```

.otherwise


  1. ```ts
  2. match(...)
  3.   .with(...)
  4.   .otherwise(defaultHandler)
  5. ```

Runs the pattern-matching expression with a default handler which will be called if no previous .with() clause match the input value, and returns the result.

Signature


  1. ```ts
  2. function otherwise(defaultHandler: (value: TInput) => TOutput): TOutput;
  3. ```

Arguments


- defaultHandler: (value: TInput) => TOutput
  - Required
  - Function called if no pattern matched the input value.
  - Think of it as the default: case of switch statements.
  - All handlers on a single match case must return values of the same type, TOutput.

.run


  1. ```ts
  2. match(...)
  3.   .with(...)
  4.   .run()
  5. ```

Runs the pattern-matching expression and returns its result. It throws an error at run time if no match was found, same as exhaustive(). However, unlike .exhaustive(), exhaustiveness is not checked at compile time, meaning the type checker will not verify that all possible cases are covered.

Signature


  1. ```ts
  2. function run(): TOutput;
  3. ```

isMatching


  1. ```ts
  2. if (isMatching(pattern, value))  {
  3.   ...
  4. }
  5. ```

isMatching is a type guard function which checks if a pattern matches a given value. It is _curried_, which means it can be used in two ways.

With a single argument:

  1. ```ts
  2. import { isMatching, P } from 'ts-pattern';

  3. const isBlogPost = isMatching({
  4.   title: P.string,
  5.   description: P.string,
  6. });

  7. if (isBlogPost(value)) {
  8.   // value: { title: string, description: string }
  9. }
  10. ```

With two arguments:

  1. ```ts
  2. const blogPostPattern = {
  3.   title: P.string,
  4.   description: P.string,
  5. };

  6. if (isMatching(blogPostPattern, value)) {
  7.   // value: { title: string, description: string }
  8. }
  9. ```

Signature


  1. ```ts
  2. export function isMatching<p extends Pattern<any>>(
  3.   pattern: p
  4. ): (value: any) => value is InvertPattern<p>;
  5. export function isMatching<p extends Pattern<any>>(
  6.   pattern: p,
  7.   value: any
  8. ): value is InvertPattern<p>;
  9. ```

Arguments


- `pattern: Pattern`
  - Required
  - The pattern a value should match.
- value?: any
  - Optional
  - if a value is given as second argument, isMatching will return a boolean telling us whether the pattern matches the value or not.
  - if we only give the pattern to the function, isMatching will return another type guard function taking a value and returning a boolean which tells us whether the pattern matches the value or not.

Patterns


A pattern is a description of the expected shape of your input value.

Patterns can be regular JavaScript values ("some string", 10, true, ...), data structures (objects, arrays, ...), wildcards ([P._](#P_-wildcard), [P.string](#pstring-wildcard), [P.number](#pnumber-wildcard), ...), or special matcher functions ([P.not](#pnot-patterns),
[P.when](#pwhen-patterns), [P.select](#pselect-patterns), ...).

All wildcards and matcher functions can be imported either as Pattern or as P from the ts-pattern module.

  1. ```ts
  2. import { match, Pattern } from 'ts-pattern';

  3. const toString = (value: unknown): string =>
  4.   match(value)
  5.     .with(Pattern.string, (str) => str)
  6.     .with(Pattern.number, (num) => num.toFixed())
  7.     .with(Pattern.boolean, (bool) => `${bool}`)
  8.     .otherwise(() => 'Unknown');
  9. ```

Or

  1. ```ts
  2. import { match, P } from 'ts-pattern';

  3. const toString = (value: unknown): string =>
  4.   match(value)
  5.     .with(P.string, (str) => str)
  6.     .with(P.number, (num) => num.toFixed())
  7.     .with(P.boolean, (bool) => `${bool}`)
  8.     .otherwise(() => 'Unknown');
  9. ```

If your input isn't typed, (if it's a any or a unknown), you are free to use any possible pattern. Your handler will infer the input type from the shape of your pattern.

Literals


Literals are primitive JavaScript values, like numbers, strings, booleans, bigints, symbols, null, undefined, or NaN.

  1. ```ts
  2. import { match } from 'ts-pattern';

  3. const input: unknown = 2;

  4. const output = match(input)
  5.   .with(2, () => 'number: two')
  6.   .with(true, () => 'boolean: true')
  7.   .with('hello', () => 'string: hello')
  8.   .with(undefined, () => 'undefined')
  9.   .with(null, () => 'null')
  10.   .with(NaN, () => 'number: NaN')
  11.   .with(20n, () => 'bigint: 20n')
  12.   .otherwise(() => 'something else');

  13. console.log(output);
  14. // => 'number: two'
  15. ```

Wildcards


P._ wildcard


The P._ pattern will match any value. You can also use P.any, which is an alias to P._.

  1. ```ts
  2. import { match, P } from 'ts-pattern';

  3. const input = 'hello';

  4. const output = match(input)
  5.   .with(P._, () => 'It will always match')
  6.   // OR
  7.   .with(P.any, () => 'It will always match')
  8.   .otherwise(() => 'This string will never be used');

  9. console.log(output);
  10. // => 'It will always match'
  11. ```

P.string wildcard


The P.string pattern will match any value of type string.

  1. ```ts
  2. import { match, P } from 'ts-pattern';

  3. const input = 'hello';

  4. const output = match(input)
  5.   .with('bonjour', () => 'Won‘t match')
  6.   .with(P.string, () => 'it is a string!')
  7.   .exhaustive();

  8. console.log(output);
  9. // => 'it is a string!'
  10. ```

P.number wildcard


The P.number pattern will match any value of type number.

  1. ```ts
  2. import { match, P } from 'ts-pattern';

  3. const input = 2;

  4. const output = match<number | string>(input)
  5.   .with(P.string, () => 'it is a string!')
  6.   .with(P.number, () => 'it is a number!')
  7.   .exhaustive();

  8. console.log(output);
  9. // => 'it is a number!'
  10. ```

P.boolean wildcard


The P.boolean pattern will match any value of type boolean.

  1. ```ts
  2. import { match, P } from 'ts-pattern';

  3. const input = true;

  4. const output = match<number | string | boolean>(input)
  5.   .with(P.string, () => 'it is a string!')
  6.   .with(P.number, () => 'it is a number!')
  7.   .with(P.boolean, () => 'it is a boolean!')
  8.   .exhaustive();

  9. console.log(output);
  10. // => 'it is a boolean!'
  11. ```

P.nullish wildcard


The P.nullish pattern will match any value of type null or undefined.

Even though null and undefined can be used as literal patterns, sometimes they appear in a union together
(e.g. null | undefined | string) and you may want to treat them as equivalent using P.nullish.

  1. ```ts
  2. import { match, P } from 'ts-pattern';

  3. const input = null;

  4. const output = match<number | null | undefined>(input)
  5.   .with(P.number, () => 'it is a number!')
  6.   .with(P.nullish, () => 'it is either null or undefined!')
  7.   .with(null, () => 'it is null!')
  8.   .with(undefined, () => 'it is undefined!')
  9.   .exhaustive();

  10. console.log(output);
  11. // => 'it is either null or undefined!'
  12. ```

P.bigint wildcard


The P.bigint pattern will match any value of type bigint.

  1. ```ts
  2. import { match, P } from 'ts-pattern';

  3. const input = 20000000n;

  4. const output = match<bigint | null>(input)
  5.   .with(P.bigint, () => 'it is a bigint!')
  6.   .otherwise(() => '?');

  7. console.log(output);
  8. // => 'it is a bigint!'
  9. ```

P.symbol wildcard


The P.symbol pattern will match any value of type symbol.

  1. ```ts
  2. import { match, P } from 'ts-pattern';

  3. const input = Symbol('some symbol');

  4. const output = match<symbol | null>(input)
  5.   .with(P.symbol, () => 'it is a symbol!')
  6.   .otherwise(() => '?');

  7. console.log(output);
  8. // => 'it is a symbol!'
  9. ```

Objects


Patterns can be objects containing sub-patterns. An object pattern will match
If and only if the input value is an object, contains all properties the pattern defines
and each property matches the corresponding sub-pattern.

  1. ```ts
  2. import { match } from 'ts-pattern';

  3. type Input =
  4.   | { type: 'user'; name: string }
  5.   | { type: 'image'; src: string }
  6.   | { type: 'video'; seconds: number };

  7. let input: Input = { type: 'user', name: 'Gabriel' };

  8. const output = match(input)
  9.   .with({ type: 'image' }, () => 'image')
  10.   .with({ type: 'video', seconds: 10 }, () => 'video of 10 seconds.')
  11.   .with({ type: 'user' }, ({ name }) => `user of name: ${name}`)
  12.   .otherwise(() => 'something else');

  13. console.log(output);
  14. // => 'user of name: Gabriel'
  15. ```

Tuples (arrays)


In TypeScript, Tuples are arrays with a fixed
number of elements which can be of different types. You can pattern-match on tuples
using a tuple pattern. A tuple pattern will match if the input value is an array of the same length,
and each item match the corresponding sub-pattern.

  1. ```ts
  2. import { match, P } from 'ts-pattern';

  3. type Input =
  4.   | [number, '+', number]
  5.   | [number, '-', number]
  6.   | [number, '*', number]
  7.   | ['-', number];

  8. const input: Input = [3, '*', 4];

  9. const output = match(input)
  10.   .with([P._, '+', P._], ([x, , y]) => x + y)
  11.   .with([P._, '-', P._], ([x, , y]) => x - y)
  12.   .with([P._, '*', P._], ([x, , y]) => x * y)
  13.   .with(['-', P._], ([, x]) => -x)
  14.   .otherwise(() => NaN);

  15. console.log(output);
  16. // => 12
  17. ```

P.array patterns


To match on arrays of unknown size, you can use P.array(subpattern).
It takes a sub-pattern, and will match if all elements in the input
array match this sub-pattern.

  1. ```ts
  2. import { match, P } from 'ts-pattern';

  3. type Input = { title: string; content: string }[];

  4. let input: Input = [
  5.   { title: 'Hello world!', content: 'This is a very interesting content' },
  6.   { title: 'Bonjour!', content: 'This is a very interesting content too' },
  7. ];

  8. const output = match(input)
  9.   .with(
  10.     P.array({ title: P.string, content: P.string }),
  11.     (posts) => 'a list of posts!'
  12.   )
  13.   .otherwise(() => 'something else');

  14. console.log(output);
  15. // => 'a list of posts!'
  16. ```

Sets


Patterns can be Sets.

  1. ```ts
  2. import { match, P } from 'ts-pattern';

  3. type Input = Set<string | number>;

  4. const input: Input = new Set([1, 2, 3]);

  5. const output = match(input)
  6.   .with(new Set([1, 'hello']), (set) => `Set contains 1 and 'hello'`)
  7.   .with(new Set([1, 2]), (set) => `Set contains 1 and 2`)
  8.   .with(new Set([P.string]), (set) => `Set contains only strings`)
  9.   .with(new Set([P.number]), (set) => `Set contains only numbers`)
  10.   .otherwise(() => '');

  11. console.log(output);
  12. // => 'Set contains 1 and 2'
  13. ```

If a Set pattern contains one single wildcard pattern, it will match if
each value in the input set match the wildcard.

If a Set pattern contains several values, it will match if the
input Set contains each of these values.

Maps


Patterns can be Maps. They match if the input is a Map, and if each
value match the corresponding sub-pattern.

  1. ```ts
  2. import { match, P } from 'ts-pattern';

  3. type Input = Map<string, string | number>;

  4. const input: Input = new Map([
  5.   ['a', 1],
  6.   ['b', 2],
  7.   ['c', 3],
  8. ]);

  9. const output = match(input)
  10.   .with(new Map([['b', 2]]), (map) => `map.get('b') is 2`)
  11.   .with(new Map([['a', P.string]]), (map) => `map.get('a') is a string`)
  12.   .with(
  13.     new Map([
  14.       ['a', P.number],
  15.       ['c', P.number],
  16.     ]),
  17.     (map) => `map.get('a') and map.get('c') are number`
  18.   )
  19.   .otherwise(() => '');

  20. console.log(output);
  21. // => 'map.get('b') is 2'
  22. ```

P.when patterns


P.when lets you define your own logic to check if the pattern should match or not.
If the predicate function given to when returns a truthy value, then the pattern
will match for this input.

Note that you can narrow down the type of your input by providing a

  1. ```ts
  2. import { match, P } from 'ts-pattern';

  3. type Input = { score: number };

  4. const output = match({ score: 10 })
  5.   .with(
  6.     {
  7.       score: P.when((score): score is 5 => score === 5),
  8.     },
  9.     (input) => '😐' // input is inferred as { score: 5 }
  10.   )
  11.   .with({ score: P.when((score) => score < 5) }, () => '😞')
  12.   .with({ score: P.when((score) => score > 5) }, () => '🙂')
  13.   .run();

  14. console.log(output);
  15. // => '🙂'
  16. ```

P.not patterns


P.not lets you match on everything but a specific value.
it's a function taking a pattern and returning the opposite pattern.

  1. ```ts
  2. import { match, P } from 'ts-pattern';

  3. type Input = boolean | number;

  4. const toNumber = (input: Input) =>
  5.   match(input)
  6.     .with(P.not(P.boolean), (n) => n) // n: number
  7.     .with(true, () => 1)
  8.     .with(false, () => 0)
  9.     .run();

  10. console.log(toNumber(2));
  11. // => 2
  12. console.log(toNumber(true));
  13. // => 1
  14. ```

P.select patterns


P.select lets you pick a piece of your input data-structure
and injects it in your handler function.

It's especially useful when pattern matching on deep data structure to
avoid the hassle of destructuring it in the handler function.

Selections can be either named (with P.select('someName')) or anonymous (with P.select()).

You can have only one anonymous selection by pattern, and the selected value will be directly inject in your handler as first argument:

  1. ```ts
  2. import { match, P } from 'ts-pattern';

  3. type Input =
  4.   | { type: 'post'; user: { name: string } }
  5.   | { ... };

  6. const input: Input = { type: 'post', user: { name: 'Gabriel' } }

  7. const output = match(input)
  8.     .with(
  9.       { type: 'post', user: { name: P.select() } },
  10.       username => username // username: string
  11.     )
  12.     .otherwise(() => 'anonymous');

  13. console.log(output);
  14. // => 'Gabriel'
  15. ```

If you need to select several things inside your input data structure, you can name your selections by giving a string to `P.select()`. Each selection will be passed as first argument to your handler in an object.

  1. ```ts
  2. import { match, P } from 'ts-pattern';

  3. type Input =
  4.   | { type: 'post'; user: { name: string }, content: string }
  5.   | { ... };

  6. const input: Input = { type: 'post', user: { name: 'Gabriel' }, content: 'Hello!' }

  7. const output = match(input)
  8.     .with(
  9.       { type: 'post', user: { name: P.select('name') }, content: P.select('body') },
  10.       ({ name, body }) => `${name} wrote "${body}"`
  11.     )
  12.     .otherwise(() => '');

  13. console.log(output);
  14. // => 'Gabriel wrote "Hello!"'
  15. ```

You can also pass a sub-pattern to P.select if you want it to only
select values which match this sub-pattern:

  1. ```ts
  2. type User = { age: number; name: string };
  3. type Post = { body: string };
  4. type Input = { author: User; content: Post };

  5. declare const input: Input;

  6. const output = match(input)
  7.   .with(
  8.     {
  9.       author: P.select({ age: P.when((age) => age > 18) }),
  10.     },
  11.     (author) => author // author: User
  12.   )
  13.   .with(
  14.     {
  15.       author: P.select('author', { age: P.when((age) => age > 18) }),
  16.       content: P.select(),
  17.     },
  18.     ({ author, content }) => author // author: User, content: Post
  19.   )
  20.   .otherwise(() => 'anonymous');
  21. ```

P.optional patterns


P.optional(subpattern) lets you annotate a key in an object pattern as being optional,
but if it is defined it should match a given sub-pattern.

  1. ```ts
  2. import { match, P } from 'ts-pattern';

  3. type Input = { key?: string | number };

  4. const output = match(input)
  5.   .with({ key: P.optional(P.string) }, (a) => {
  6.     return a.key; // string | undefined
  7.   })
  8.   .with({ key: P.optional(P.number) }, (a) => {
  9.     return a.key; // number | undefined
  10.   })
  11.   .exhaustive();
  12. ```

P.instanceOf patterns


The P.instanceOf function lets you build a pattern to check if
a value is an instance of a class:

  1. ```ts
  2. import { match, P } from 'ts-pattern';

  3. class A {
  4.   a = 'a';
  5. }
  6. class B {
  7.   b = 'b';
  8. }

  9. type Input = { value: A | B };

  10. const input: Input = { value: new A() };

  11. const output = match(input)
  12.   .with({ value: P.instanceOf(A) }, (a) => {
  13.     return 'instance of A!';
  14.   })
  15.   .with({ value: P.instanceOf(B) }, (b) => {
  16.     return 'instance of B!';
  17.   })
  18.   .exhaustive();

  19. console.log(output);
  20. // => 'instance of A!'
  21. ```

P.union patterns


P.union(...subpatterns) lets you test several patterns and will match if
one of these patterns do. It's particularly handy when you want to handle
some cases of a union type in the same code branch:

  1. ```ts
  2. import { match, P } from 'ts-pattern';

  3. type Input =
  4.   | { type: 'user'; name: string }
  5.   | { type: 'org'; name: string }
  6.   | { type: 'text'; content: string }
  7.   | { type: 'img'; src: string };

  8. declare const input: Input;

  9. const output = match(input)
  10.   .with({ type: P.union('user', 'org') }, (userOrOrg) => {
  11.     // userOrOrg: User | Org
  12.     return userOrOrg.name;
  13.   })
  14.   .otherwise(() => '');
  15. ```

P.intersection patterns


P.intersection(...subpatterns) lets you ensure that the input matches
all sub-patterns passed as parameters.

  1. ```ts
  2. class A {
  3.   constructor(public foo: 'bar' | 'baz') {}
  4. }

  5. class B {
  6.   constructor(public str: string) {}
  7. }

  8. type Input = { prop: A | B };

  9. declare const input: Input;

  10. const output = match(input)
  11.   .with(
  12.     { prop: P.intersection(P.instanceOf(A), { foo: 'bar' }) },
  13.     ({ prop }) => prop.foo // prop: A & { foo: 'bar' }
  14.   )
  15.   .with(
  16.     { prop: P.intersection(P.instanceOf(A), { foo: 'baz' }) },
  17.     ({ prop }) => prop.foo // prop: A & { foo: 'baz' }
  18.   )
  19.   .otherwise(() => '');
  20. ```

Types


P.infer


`P.infer` lets you infer a type of value from a type of pattern.

It's particularly useful when validating an API response.

  1. ```ts
  2. const postPattern = {
  3.   title: P.string,
  4.   content: P.string,
  5.   likeCount: P.number,
  6.   author: {
  7.     name: P.string,
  8.   },
  9. };

  10. type Post = P.infer<typeof postPattern>;

  11. // posts: Post[]
  12. const posts = await fetch(someUrl)
  13.   .then((res) => res.json())
  14.   .then((res: unknown): Post[] =>
  15.     isMatching({ data: P.array(postPattern) }, res) ? res.data : []
  16.   );
  17. ```

P.Pattern


`P.Pattern` is the type of all possible pattern for a generic type `T`.

  1. ```ts
  2. type User = { name: string; age: number };

  3. const userPattern: Pattern<User> = {
  4.   name: 'Alice',
  5. };
  6. ```

Type inference


TS-Pattern takes advantage of some of the most advanced features of the type system to narrow the input type using the current pattern. It is also able to accurately know if you have handled all cases, even when matching on complex data-structures.

Here are some examples of TS-Pattern's inference features.

Type narrowing


If you pattern-match on a union type with a discriminant property, TS-Pattern will use this discriminant to narrow the type of input.

  1. ```ts
  2. type Text = { type: 'text'; data: string };
  3. type Img = { type: 'img'; data: { src: string; alt: string } };
  4. type Video = { type: 'video'; data: { src: string; format: 'mp4' | 'webm' } };
  5. type Content = Text | Img | Video;

  6. const formatContent = (content: Content): string =>
  7.   match(content)
  8.     .with({ type: 'text' }, (text /* : Text */) => '<p>...</p>')
  9.     .with({ type: 'img' }, (img /* : Img */) => '<img ... />')
  10.     .with({ type: 'video' }, (video /* : Video */) => '<video ... />')
  11.     .with(
  12.       { type: 'img' },
  13.       { type: 'video' },
  14.       (video /* : Img | Video */) => 'img or video'
  15.     )
  16.     .with(
  17.       { type: P.union('img', 'video') },
  18.       (video /* : Img | Video */) => 'img or video'
  19.     )
  20.     .exhaustive();
  21. ```

If you use P.select, TS-Pattern will pick up the type of the property you selected, and will inferyour handler's type accordingly.

  1. ```ts
  2. const formatContent = (content: Content): string =>
  3.   match(content)
  4.     .with(
  5.       { type: 'text', data: P.select() },
  6.       (content /* : string */) => '<p>...</p>'
  7.     )
  8.     .with(
  9.       { type: 'video', data: { format: P.select() } },
  10.       (format /* : 'mp4' | 'webm' */) => '<video ... />'
  11.     )
  12.     .with(
  13.       { type: P.union('img', 'video'), data: P.select() },
  14.       (data /* : Img['data'] | Video['data'] */) => 'img or video'
  15.     )
  16.     .exhaustive();
  17. ```

If the function given to P.when is a Type Guard, TS-Pattern will use the type guard's return type to narrow the input.

  1. ```ts
  2. const isString = (x: unknown): x is string => typeof x === 'string';

  3. const isNumber = (x: unknown): x is number => typeof x === 'number';

  4. const fn = (input: { id: number | string }) =>
  5.   match(input)
  6.     .with({ id: P.when(isString) }, (narrowed /* : { id: string } */) => 'yes')
  7.     .with({ id: P.when(isNumber) }, (narrowed /* : { id: number } */) => 'yes')
  8.     .exhaustive();
  9. ```

Exhaustiveness checking


If your data structure contains several union types, you can pattern-match on several of them with a single pattern. TS-Pattern will keep track of the cases which have been handled and those which
haven't, so you never forget to handle a case.

  1. ```ts
  2. type Permission = 'editor' | 'viewer';
  3. type Plan = 'basic' | 'pro';

  4. const fn = (org: Plan, user: Permission): string =>
  5.   match([org, user] as const)
  6.     .with(['basic', 'viewer'], () => {})
  7.     .with(['basic', 'editor'], () => {})
  8.     .with(['pro', 'viewer'], () => {})
  9.     // Fails with `NonExhaustiveError<['pro', 'editor']>`
  10.     // because the `['pro', 'editor']` case isn't handled.
  11.     .exhaustive();
  12. ```

Want to learn how TS-Pattern is built?


Check out 👉 Type-Level TypeScript, an online course to learn how to take full advantage of the most advanced features of TypeScript!

Inspirations


This library has been heavily inspired by this great article by Wim Jongeneel:
It made me realize pattern matching could be implemented in userland and we didn't have
to wait for it to be added to the language itself. I'm really grateful for that 🙏