Skip to Content
With

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, the with clause 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.
  • TInput might be narrowed to a more precise type using the pattern.

handler: (selections: Selections<TInput>, value: TInput) => TOutput

  • Required
  • Function called when the match conditions are satisfied.
  • All handlers on a single match case must return values of the same type, TOutput.
  • selections is an object of properties selected from the input with the P.select() function.
  • TInput might be narrowed to a more precise type using the pattern.

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);