match
match() associates a pattern with a function and returns a PatternResult when the value matches this pattern. Use it:
- as a builder (
P.match(input)), to chain several.with()/.when()before concluding with.otherwise()or.exhaustive(); - in functional form to plug a step directly into a
pipe(P.match(pattern, fn)orP.match(input, pattern, fn)).
Interactive example
Builder version
Syntax
Classic signature
typescript
function match<
GenericInput extends AnyValue,
GenericInputValue extends Exclude<GenericInput, PatternResult>,
GenericInputPatternResult extends Extract<GenericInput, PatternResult>,
const GenericPattern extends Pattern<GenericInputValue>,
GenericPatternValue extends PatternValue<GenericPattern>,
GenericOutput extends AnyValue | EscapeVoid,
GenericMatchedValue extends Extract<ComplexMatchedValue<GenericInputValue, GenericPatternValue>, any>
>(
input: GenericInput | PatternResult<unknown>,
pattern: FixDeepFunctionInfer<Pattern<GenericInputValue>, GenericPattern>,
theFunction: (value: ComplexMatchedValue<...>) => GenericOutput
): BreakGenericLink<
PatternResult<GenericOutput> | GenericInputPatternResult | ComplexUnMatchedValue<...>
>;Curried signature
typescript
function match<
GenericInput extends AnyValue,
...
>(
pattern: FixDeepFunctionInfer<Pattern<GenericInputValue>, GenericPattern>,
theFunction: (value: ComplexMatchedValue<...>) => GenericOutput
): (
input: GenericInput | PatternResult<unknown>
) => BreakGenericLink<
PatternResult<GenericOutput> | GenericInputPatternResult | ComplexUnMatchedValue<...>
>;Builder signature
typescript
function match<
GenericInput extends AnyValue
>(input: GenericInput): MatchBuilder<GenericInput>Matched automatically corresponds to the portion of the union actually covered by the pattern (parts of an object, tuple, literals, predicates, or ToolPattern).
Parameters
input(builder version or direct invocation): value to analyze. Can already be aPatternResult(chaining).pattern: pattern to compare (literal, tuple, object, predicate function, pattern created viaP.union, etc.).theFunction: transformation executed if the pattern matches. The parameter is typed with the exact shape of the pattern.
Return value
- Builder: a
MatchBuilderwith.with(),.when(),.otherwise()and.exhaustive(). - Functional version: either a
PatternResult<Output>if the pattern matches, or the original value (or what remains of the union) if the pattern does not match. This result can be chained withwhen,otherwiseorexhaustive.
Best practices
- Break down your unions by object patterns
{ type: "..." }rather thanif/else, to benefit from structural inference (direct access to payload). - Combine
match(pattern, fn)in apipeto trigger processing only when a specific pattern appears along the pipeline. - Always add an
otherwiseor anexhaustive()on the builder version so nothing is left unhandled.
See also
when– Adds a custom guard.otherwise– Ends the pipeline with a fallback.exhaustive– Forces total coverage of cases.
