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.
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.
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!
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.
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.
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>.
.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:
.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:
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:
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:
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:
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
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.
.with(P._, () => state) // You could also use it inside another pattern: .with([P._, P._], () => state) // at any level: .with([P._, { type: P._ }], () => state)
.exhaustive(), .otherwise() and .run()
.exhaustive();
.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 slightly 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().
.otherwise(() => state);
Matching several patterns
As you may know, switch statements allow handling several cases with
the same code block:
switch (type) { case 'text': case 'span': case 'p': return 'text'; case 'btn': case 'button': return 'button';}
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:
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.
.returnType
match(...) .returnType<string>() .with(..., () => "has to be a string") .with(..., () => "Oops".length) // ~~~~~~~~~~~~~ ❌ `number` isn't a string!
The .returnType<SomeType>() method allows you to control the return type of all of your branches of code. It accepts a single type parameter that will be used as the return type of your match expression. All code branches must return values assignable to this type.
Signature
function returnType<TOutputOverride>(): Match<TInput, TOutputOverride>;
Type arguments
TOutputOverride
The type that your match expression will return. All branches must return values assignable to it.
.exhaustive
match(...) .with(...) .exhaustive()
Runs the pattern-matching expression and returns its result. It also enables exhaustiveness checking, making sure that we have handled all possible cases at compile time.
By default, .exhaustive() will throw an error if the input value wasn't handled by any .with(...) clause. This should only happen if your types are incorrect.
It is possible to pass your own handler function as a parameter to decide what should happen if an unexpected value has been received. You can for example throw your own custom error:
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
function otherwise(defaultHandler: (value: TInput) => TOutput): TOutput;
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
match(...) .with(...) .run()
returns the result of the pattern-matching expression, or throws if no pattern matched the input. .run() is similar to .exhaustive(), but is unsafe because exhaustiveness is not checked at compile time, so you have no guarantees that all cases are indeed covered. Use at your own risks.
Signature
function run(): TOutput;
.narrow
match(...) .with(...) .narrow() .with(...)
The .narrow() method deeply narrows the input type to exclude all values that have previously been handled. This is useful when you want to exclude cases from union types or nullable properties that are deeply nested.
Note that handled case of top-level union types are excluded by default, without calling .narrow().
Signature
function narrow(): Match<Narrowed<TInput>, TOutput>;
export function isMatching<p extends Pattern<any>>( pattern: p): (value: any) => value is InvertPattern<p>;export function isMatching<p extends Pattern<any>>( pattern: p, value: any): value is InvertPattern<p>;
Arguments
pattern: Pattern<any>
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.string, P.number, ...), or special matcher functions (P.not,
P.when, P.select, ...).
All wildcards and matcher functions can be imported either as Pattern or as P from the ts-pattern module.
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.
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.
In TypeScript, Tuples are arrays with a fixed
number of elements that 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 matches the corresponding sub-pattern.
The P._ pattern will match any value. You can also use P.any, which is an alias to P._.
import { match, P } from 'ts-pattern';const input = 'hello';const output = match(input) .with(P._, () => 'It will always match') // OR .with(P.any, () => 'It will always match') .otherwise(() => 'This string will never be used');console.log(output);// => 'It will always match'
P.string wildcard
The P.string pattern will match any value of type string.
import { match, P } from 'ts-pattern';const input = 'hello';const output = match(input) .with('bonjour', () => 'Won‘t match') .with(P.string, () => 'it is a string!') .exhaustive();console.log(output);// => 'it is a string!'
P.number wildcard
The P.number pattern will match any value of type number.
import { match, P } from 'ts-pattern';const input = 2;const output = match<number | string>(input) .with(P.string, () => 'it is a string!') .with(P.number, () => 'it is a number!') .exhaustive();console.log(output);// => 'it is a number!'
P.boolean wildcard
The P.boolean pattern will match any value of type boolean.
import { match, P } from 'ts-pattern';const input = true;const output = match<number | string | boolean>(input) .with(P.string, () => 'it is a string!') .with(P.number, () => 'it is a number!') .with(P.boolean, () => 'it is a boolean!') .exhaustive();console.log(output);// => 'it is a boolean!'
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.
import { match, P } from 'ts-pattern';const input = null;const output = match<number | null | undefined>(input) .with(P.number, () => 'it is a number!') .with(P.nullish, () => 'it is either null or undefined!') .exhaustive();console.log(output);// => 'it is either null or undefined!'
P.nonNullable wildcard
The P.nonNullable pattern will match any value except null or undefined.
import { match, P } from 'ts-pattern';const input = null;const output = match<number | null | undefined>(input) .with(P.nonNullable, () => 'it is a number!') .otherwise(() => 'it is either null or undefined!');console.log(output);// => 'it is either null or undefined!'
P.bigint wildcard
The P.bigint pattern will match any value of type bigint.
import { match, P } from 'ts-pattern';const input = 20000000n;const output = match<bigint | null>(input) .with(P.bigint, () => 'it is a bigint!') .otherwise(() => '?');console.log(output);// => 'it is a bigint!'
P.symbol wildcard
The P.symbol pattern will match any value of type symbol.
import { match, P } from 'ts-pattern';const input = Symbol('some symbol');const output = match<symbol | null>(input) .with(P.symbol, () => 'it is a symbol!') .otherwise(() => '?');console.log(output);// => 'it is a symbol!'
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.
import { match, P } from 'ts-pattern';type Input = { title: string; content: string }[];let input: Input = [ { title: 'Hello world!', content: 'This is a very interesting content' }, { title: 'Bonjour!', content: 'This is a very interesting content too' },];const output = match(input) .with( P.array({ title: P.string, content: P.string }), (posts) => 'a list of posts!' ) .otherwise(() => 'something else');console.log(output);// => 'a list of posts!'
Matching variadic tuples with P.array
In TypeScript, Variadic Tuple Types are array types created with the ... spread operator, like [string, ...string[]], [number, ...boolean[], string] etc. You can match against variadic tuple types using array literals containing ...P.array(subpattern):
import { match, P } from 'ts-pattern';type Input = (number | string)[];declare const input: Input;const output = match(input) // P.array's parameter is optional .with([P.string, ...P.array()], (input) => input) // input: [string, ...(number | string)[]] .with(['print', ...P.array(P.string)], (input) => input) // input: ['print', ...string[]] // you can put patterns on either side of `...P.array()`: .with([...P.array(P.string), 'end'], (input) => input) // input: [...string[], 'end'] .with(['start', ...P.array(P.string), 'end'], (input) => input) // input: ['start', ...string[], 'end'] .otherwise((input) => input);
P.record patterns
To match a Record<Key, Value> (an object with consistent key and value types), you can use P.record(keyPattern, valuePattern).
It takes a sub-pattern to match against the key, a sub-pattern to match against the value, and will match if all entries in the object
match these two sub-patterns.
import { match, P } from 'ts-pattern';type Input = Record<string, number>;const input: Input = { alice: 100, bob: 85, charlie: 92,};const output = match(input) .with(P.record(P.string, P.number), (scores) => `All user scores`) .with(P.record(P.string, P.string), (names) => `All user names`) .otherwise(() => '');console.log(output);// => "All user scores"
You can also use P.record with a single argument P.record(valuePattern), which assumes string keys:
const userProfiles = { alice: { name: 'Alice', age: 25 }, bob: { name: 'Bob', age: 30 },};const output = match(userProfiles) .with( P.record({ name: P.string, age: P.number }), (profiles) => `User profiles with name and age` ) .otherwise(() => 'Different format');console.log(output);// => "User profiles with name and age"
When using P.select in record patterns, you can extract all keys or all values as arrays:
To match a Set, you can use P.set(subpattern).
It takes a sub-pattern, and will match if all elements inside the set
match this sub-pattern.
import { match, P } from 'ts-pattern';type Input = Set<string | number>;const input: Input = new Set([1, 2, 3]);const output = match(input) .with(P.set(1), (set) => `Set contains only 1`) .with(P.set(P.string), (set) => `Set contains only strings`) .with(P.set(P.number), (set) => `Set contains only numbers`) .otherwise(() => '');console.log(output);// => "Set contains only numbers"
P.map patterns
To match a Map, you can use P.map(keyPattern, valuePattern).
It takes a subpattern to match against the key, a subpattern to match agains the value, and will match if all elements inside this map
match these two sub-patterns.
import { match, P } from 'ts-pattern';type Input = Map<string, string | number>;const input: Input = new Map([ ['a', 1], ['b', 2], ['c', 3],]);const output = match(input) .with(P.map(P.string, P.number), (map) => `map's type is Map<string, number>`) .with(P.map(P.string, P.string), (map) => `map's type is Map<string, string>`) .with( P.map(P.union('a', 'c'), P.number), (map) => `map's type is Map<'a' | 'c', number>` ) .otherwise(() => '');console.log(output);// => "map's type is Map<string, number>"
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
Type Guard function to P.when.
import { match, P } from 'ts-pattern';type Input = { score: number };const output = match<Input>({ score: 10 }) .with( { score: P.when((score): score is 5 => score === 5), }, (input) => '😐' // input is inferred as { score: 5 } ) .with({ score: P.when((score) => score < 5) }, () => '😞') .otherwise(() => '🙂');console.log(output);// => '🙂'
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.
If you need to select several things inside your input data structure, you can name your selections by giving a string to P.select(<name>). Each selection will be passed as first argument to your handler in an object.
The P.instanceOf function lets you build a pattern to check if
a value is an instance of a class:
import { match, P } from 'ts-pattern';class A { a = 'a';}class B { b = 'b';}type Input = { value: A | B };const input: Input = { value: new A() };const output = match(input) .with({ value: P.instanceOf(A) }, (a) => { return 'instance of A!'; }) .with({ value: P.instanceOf(B) }, (b) => { return 'instance of B!'; }) .exhaustive();console.log(output);// => 'instance of A!'
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:
Note that most of the time, the match and isMatching functions perform narrowing for you, and you do not need to narrow types yourself.
P.Pattern
P.Pattern<T> is the type of all possible pattern for a generic type T.
type User = { name: string; age: number };const userPattern: Pattern<User> = { name: 'Alice',};
Type inference
TS-Pattern takes advantage the most advanced features of TypeScript to perform type narrowing and accurate exhaustive matching, even when matching on complex data-structures.
Here are some examples of TS-Pattern's type inference features.
Type narrowing
When pattern-matching on a input containing union types, TS-Pattern will infer the most precise type possible for the argument of your handler function using the pattern you provide.
When using P.select in a pattern, TS-Pattern will find and inject the selected value in your handler. The type of your handler's argument is inferred accordingly.
If you pass a type guard function to P.when, TS-Pattern will use its return type to narrow the input.
const isString = (x: unknown): x is string => typeof x === 'string';const isNumber = (x: unknown): x is number => typeof x === 'number';const fn = (input: { id: number | string }) => match(input) .with({ id: P.when(isString) }, (narrowed /* : { id: string } */) => 'yes') .with({ id: P.when(isNumber) }, (narrowed /* : { id: number } */) => 'yes') .exhaustive();
Exhaustiveness checking
TS-Pattern will keep track of handled and unhandled cases of your input type. Even when pattern-matching on several union types at once, you only need to call .exhaustive() to make sure that all possible cases are correctly handled.
type Permission = 'editor' | 'viewer';type Plan = 'basic' | 'pro';const fn = (org: Plan, user: Permission): string => match([org, user]) .with(['basic', 'viewer'], () => {}) .with(['basic', 'editor'], () => {}) .with(['pro', 'viewer'], () => {}) // Fails with `NonExhaustiveError<['pro', 'editor']>` // because the `['pro', 'editor']` case isn't handled. .exhaustive();
Inspirations
This library has been heavily inspired by this great article by Wim Jongeneel:
Pattern Matching in TypeScript with Record and Wildcard Patterns.
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 🙏