Last Updated: 3/18/2026
.with() Method
The .with() method adds a pattern matching case to your match expression. When the pattern matches the input value, the corresponding handler function is called.
Basic Usage
match(input)
.with(pattern, handler)
.with(pattern, guardFunction, handler)
.with(pattern1, pattern2, pattern3, handler)Signatures
Single Pattern
function with(
pattern: Pattern<TInput>,
handler: (selections: Selections<TInput>, value: TInput) => TOutput
): Match<TInput, TOutput>;Multiple Patterns
function with(
pattern1: Pattern<TInput>,
...patterns: Pattern<TInput>[],
handler: (value: TInput) => TOutput
): Match<TInput, TOutput>;With Guard Function
function with(
pattern: Pattern<TInput>,
when: (value: TInput) => unknown,
handler: (selection: Selection<TInput>, value: TInput) => TOutput
): Match<TInput, TOutput>;Arguments
pattern(Required): The pattern your input must match for the handler to be calledwhen(Optional): Additional guard function that must return a truthy valuehandler(Required): Function called when the match conditions are satisfied
Handler Function
The handler receives:
- First argument: Selected values (if using
P.select()) or the narrowed input value - Second argument: The full input value with narrowed type
.with(
{ type: 'user', name: P.select() },
(name, fullInput) => {
// name: string (selected value)
// fullInput: { type: 'user', name: string } (narrowed input)
}
)Examples
Basic Pattern Matching
const sanitize = (name: string) =>
match(name)
.with('text', () => 'text-element')
.with('span', () => 'text-element')
.with('button', () => 'button-element')
.otherwise(() => name);Multiple Patterns (OR Logic)
Handle several cases with the same handler:
const sanitize = (name: string) =>
match(name)
.with('text', 'span', 'p', () => 'text')
.with('btn', 'button', () => 'button')
.otherwise(() => name);With Guard Function
Add additional runtime conditions:
match(input)
.with(
{ status: 'loading' },
(input) => input.startTime + 2000 < Date.now(),
() => 'timeout'
)
.otherwise(() => 'ok');Selecting Values
Extract specific parts of the input:
match(input)
.with(
{ type: 'error', error: P.select() },
(error) => `Error: ${error.message}`
)
.with(
{ type: 'user', name: P.select('name'), id: P.select('id') },
({ name, id }) => `User ${name} (${id})`
)
.otherwise(() => 'unknown');Type Safety
The input type is automatically narrowed based on your pattern:
type Input =
| { type: 'text'; content: string }
| { type: 'img'; src: string };
match(input)
.with({ type: 'text' }, (input) => {
// input is narrowed to { type: 'text'; content: string }
return input.content;
})
.with({ type: 'img' }, (input) => {
// input is narrowed to { type: 'img'; src: string }
return input.src;
})
.exhaustive();