Last Updated: 3/6/2026
Getting Started with TS-Pattern
Your First Pattern Match
Let’s create a simple pattern matching example:
import { match } from 'ts-pattern';
const input: unknown = 2;
const output = match(input)
.with(2, () => 'number: two')
.with(true, () => 'boolean: true')
.with('hello', () => 'string: hello')
.otherwise(() => 'something else');
console.log(output); // => 'number: two'Example: A State Reducer
Let’s create a state reducer for a frontend application that fetches some data. Our application can be in four different states: idle, loading, success and error.
Define Your Types
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' };Create the Reducer
import { match, P } from 'ts-pattern';
const reducer = (state: State, event: Event) =>
match([state, event])
.returnType<State>()
.with(
[{ status: 'loading' }, { type: 'success' }],
([_, event]) => ({ status: 'success', data: event.data })
)
.with(
[{ status: 'loading' }, { type: 'error', error: P.select() }],
(error) => ({ status: 'error', error })
)
.with(
[{ status: P.not('loading') }, { type: 'fetch' }],
() => ({ status: 'loading', startTime: Date.now() })
)
.with(
[
{
status: 'loading',
startTime: P.when((t) => t + 2000 < Date.now()),
},
{ type: 'cancel' },
],
() => ({ status: 'idle' })
)
.with(P._, () => state)
.exhaustive();Key Concepts
1. match(value)
match takes a value and returns a builder on which you can add your pattern matching cases.
2. .with(pattern, handler)
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.
3. .exhaustive() or .otherwise()
.exhaustive() executes the pattern matching expression and returns the result. It also enables exhaustiveness checking, making sure we don’t forget any possible case.
.otherwise() takes a handler function returning a default value, equivalent to .with(P._, handler).exhaustive().
Next Steps
- Learn about Patterns
- Explore the API Reference
- Check out Examples