Last Updated: 3/18/2026
match() Function
The match function is the entry point for creating pattern matching expressions. It takes a value and returns a builder on which you can add your pattern matching cases.
Basic Usage
import { match } from 'ts-pattern';
const result = match(value)
.with(pattern1, handler1)
.with(pattern2, handler2)
.otherwise(defaultHandler);Signature
function match<TInput, TOutput>(input: TInput): Match<TInput, TOutput>;Arguments
input(Required): The input value your patterns will be tested against
Return Value
Returns a Match object on which you can call:
.with()- Add pattern matching cases.when()- Add predicate-based cases.returnType()- Specify the return type.exhaustive()- Execute with exhaustiveness checking.otherwise()- Execute with a default handler.run()- Execute without exhaustiveness checking.narrow()- Narrow the input type
Examples
Basic Example
const output = match(input)
.with(2, () => 'number: two')
.with(true, () => 'boolean: true')
.with('hello', () => 'string: hello')
.otherwise(() => 'something else');Matching on Objects
type Input =
| { type: 'user'; name: string }
| { type: 'image'; src: string };
const output = match(input)
.with({ type: 'image' }, () => 'image')
.with({ type: 'user' }, ({ name }) => `user: ${name}`)
.exhaustive();Matching on Tuples
const output = match([state, event])
.with([{ status: 'loading' }, { type: 'success' }], () => ...)
.with([{ status: 'idle' }, { type: 'fetch' }], () => ...)
.exhaustive();Type Inference
match automatically infers both the input and output types from your patterns and handlers. You can also specify them explicitly if needed:
match<InputType, OutputType>(input)
.with(...)
.exhaustive();However, explicit type parameters are usually unnecessary as TS-Pattern can infer them accurately.