Last Updated: 3/6/2026
.with()
Match a pattern and execute a handler if the pattern matches.
Signature
function with(
pattern: Pattern<TInput>,
handler: (selections: Selections<TInput>, value: TInput) => TOutput
): Match<TInput, TOutput>;
// Overload for multiple patterns
function with(
pattern1: Pattern<TInput>,
...patterns: Pattern<TInput>[],
handler: (value: TInput) => TOutput
): Match<TInput, TOutput>;
// Overload for guard functions
function with(
pattern: Pattern<TInput>,
when: (value: TInput) => unknown,
handler: (selection: Selection<TInput>, value: TInput) => TOutput
): Match<TInput, TOutput>;Arguments
pattern: Pattern<TInput>
- Required
- The pattern your input must match for the handler to be called.
- If you provide several patterns before providing the
handler, thewithclause 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.
TInputmight be narrowed to a more precise type using thepattern.
handler: (selections: Selections<TInput>, value: TInput) => TOutput
- Required
- Function called when the match conditions are satisfied.
- All handlers on a single
matchcase must return values of the same type,TOutput. selectionsis an object of properties selected from the input with theP.select()function.TInputmight be narrowed to a more precise type using thepattern.
Examples
Basic Pattern Matching
import { match } from 'ts-pattern';
type Content = { type: 'text'; data: string } | { type: 'img'; src: string };
const formatContent = (content: Content) =>
match(content)
.with({ type: 'text' }, (text) => `<p>${text.data}</p>`)
.with({ type: 'img' }, (img) => `<img src="${img.src}" />`)
.exhaustive();Multiple Patterns
const sanitize = (name: string) =>
match(name)
.with('text', 'span', 'p', () => 'text')
.with('btn', 'button', () => 'button')
.otherwise(() => name);
sanitize('span'); // 'text'
sanitize('button'); // 'button'With Guard Function
match(value)
.with(
{ status: 'loading' },
(state) => state.startTime + 2000 < Date.now(),
() => ({ status: 'idle' })
)
.otherwise(() => value);