onrails logoonrails

@onrails/pattern API

Complete API reference for @onrails/pattern

@onrails/pattern API Reference

Matching

match ƒ

Start a pattern-matching expression. Two call shapes:

  • match(value) — data-first; subsequent .exhaustive() or .otherwise(fn) runs immediately against value.
  • match<T>() — curried; subsequent .exhaustive() returns a function (value: T) => R for use in pipe(...) or as a reusable matcher.
function match<T>(input: T): MatchBuilder<T, never, true, [], false>
function match<T = never>(): MatchBuilder<T, never, false, [], false>

Parameters

ParameterTypeDescription
inputT

Example

// Data-first
const out = match({ kind: "click", x: 1, y: 2 } as Event)
  .with({ kind: "click" }, (e) => e.x + e.y)
  .with({ kind: "key" },   () => -1)
  .exhaustive();

// Curried — build a reusable matcher
const describe = match<Event>()
  .with({ kind: "click" }, (e) => `click @ ${e.x},${e.y}`)
  .with({ kind: "key" },   (e) => `key ${e.code}`)
  .exhaustive();

MatchBuilder class

Fluent builder for match. Tracks the handled cases at the type level so .exhaustive() only compiles when every union member is covered.

The Locked phantom flag (set via .returnType<R>()) constrains every subsequent handler to return R, useful when branch return-type inference would widen to a union narrower than the target slot (e.g. ReactNode, an API DTO).

class MatchBuilder

Example

const describe = match<Event>()
  .with({ kind: "click" }, (e) => `click @ ${e.x},${e.y}`)
  .with({ kind: "key" },   (e) => `key ${e.code}`)
  .exhaustive();

new MatchBuilder constructor

constructor<T, R = never, HasInput extends boolean = false, Handled extends readonly unknown[] = [], Locked extends boolean = false>(cases: Case<T, unknown>[], input: T | typeof NO_INPUT, _handled?: Handled): MatchBuilder<T, R, HasInput, Handled, Locked>

MatchBuilder.prototype._handled ƒ

Phantom tuple of handled cases — only its compile-time contents matter.

_handled: Handled

MatchBuilder.prototype.with ƒ

Add a case: when input satisfies pattern, run handler on the narrowed value. The pattern may be a literal, a shallow object pattern, or a guard (Pattern); a type-predicate guard narrows the handler input. Each .with advances compile-time exhaustiveness tracking so .exhaustive() knows which union members remain.

with<const P extends Pattern<T>, R2>(pattern: P, handler: (input: Narrow<T, P>) => HandlerReturn<Locked, R, R2>): MatchBuilder<T, NextResult<Locked, R, R2>, HasInput, readonly [......], Locked>

Parameters

ParameterTypeDescription
patternP- literal, object pattern, or guard to test against
handler(input: Narrow<T, P>) => HandlerReturn<Locked, R, R2>- run on the narrowed input when the pattern matches

Returns

a builder with this case appended

Example

type Event =
  | { type: "message"; content: string }
  | { type: "error"; message: string }
  | { type: "done" };

const summary = match({ type: "message", content: "hi" } as Event)
  .with({ type: "message" }, (e) => e.content)   // e: { type: "message"; content: string }
  .with({ type: "error" },   (e) => e.message)
  .with({ type: "done" },    () => "—")
  .exhaustive();                                 // "hi"

MatchBuilder.prototype.withOneOf ƒ

One handler for several patterns (OR). The handler input is the union of the members narrowed by each pattern, and all of them are marked handled for exhaustiveness.

withOneOf<const Ps extends readonly Pattern<T>[], R2>(patterns: Ps, handler: (input: NarrowUnion<T, Ps>) => HandlerReturn<Locked, R, R2>): MatchBuilder<T, NextResult<...>, HasInput, readonly [......], Locked>

Parameters

ParameterTypeDescription
patternsPs- patterns to test; any match runs handler
handler(input: NarrowUnion<T, Ps>) => HandlerReturn<Locked, R, R2>- run on the union of narrowed members

Returns

a builder with the shared case appended

Example

type Job =
  | { kind: "queued"; id: string }
  | { kind: "running"; id: string }
  | { kind: "done"; ok: boolean };

const status = match({ kind: "running", id: "j1" } as Job)
  .withOneOf([{ kind: "queued" }, { kind: "running" }], (j) => j.id) // j: queued | running
  .with({ kind: "done" }, (j) => (j.ok ? "yes" : "no"))
  .exhaustive();                                                      // "j1"

MatchBuilder.prototype.withEither ƒ

withOneOf for exactly two patterns — sugar that avoids the array.

withEither<const P1 extends Pattern<T>, const P2 extends Pattern<T>, R2>(pattern1: P1, pattern2: P2, handler: (input: NarrowUnion<T, readonly [P1, P2]>) => HandlerReturn<Locked, R, R2>): MatchBuilder<...>

Parameters

ParameterTypeDescription
pattern1P1- first pattern
pattern2P2- second pattern
handler(input: NarrowUnion<T, readonly [P1, P2]>) => HandlerReturn<Locked, R, R2>- run on the union of the two narrowed members

Returns

a builder with the shared case appended

Example

type Provider = "ollama" | "openrouter";

const pick = match<Provider>()
  .withEither("ollama", "openrouter", (p) => p) // p: "ollama" | "openrouter"
  .exhaustive();
pick("ollama"); // "ollama"

MatchBuilder.prototype.returnType ƒ

Lock the result type. All subsequent .with() handlers must return R2. Useful when branch return-type inference widens to a union narrower than the slot the match feeds into (e.g. ReactNode).

Also the fix for literal-widening: when a handler returns an object whose field is a union literal, inference widens it (e.g. { mode: "native" } becomes { mode: string }, breaking a Mode union). Lock the target type instead of sprinkling as const:

returnType<R2>(): MatchBuilder<T, R2, HasInput, Handled, true>

Example

type State = { mode: "compat" | "native" };
const next = match(flag)
  .returnType<State>()                       // handlers now checked against State
  .with("--native", () => ({ mode: "native" })) // no `as const` needed
  .otherwise(() => state);

MatchBuilder.prototype.run ƒ

Run the accumulated cases now, without a compile-time exhaustiveness check. Uses the value passed to match (data-first), or the value passed to run (curried). Throws "Non-exhaustive match" if no case matches at runtime — prefer exhaustive when the input is a closed union, or otherwise for an explicit fallback.

run(...input: readonly [input: T] | readonly []): R

Parameters

ParameterTypeDescription
inputreadonly [input: T] | readonly []- the value to match when the builder was created curried

Returns

the matched handler's result

Example

type Event = { type: "error"; message: string } | { type: "done" };

const msg = match({ type: "error", message: "x" } as Event)
  .with({ type: "error" }, (e) => e.message)
  .run({ type: "error", message: "net" }); // "net"

MatchBuilder.prototype.exhaustive ƒ

Settle the match with a compile-time exhaustiveness guarantee. Only type-checks when every member of T has been handled; otherwise the return type becomes NonExhaustiveError, surfacing the missing cases as a type error. Returns the result directly when data-first (match called with a value), or a reusable (input: T) => R matcher when curried.

exhaustive(): ExhaustiveResult<T, Handled, R, HasInput>

Returns

the result (data-first) or a matcher function (curried)

Example

type Event =
  | { type: "message"; content: string }
  | { type: "error"; message: string }
  | { type: "done" };

// Curried — reusable matcher; omitting a `.with` would be a type error.
const describe = match<Event>()
  .with({ type: "message" }, (e) => e.content)
  .with({ type: "error" },   (e) => `! ${e.message}`)
  .with({ type: "done" },    () => "done")
  .exhaustive();
describe({ type: "done" }); // "done"

MatchBuilder.prototype.otherwise ƒ

Settle the match with a catch-all fallback, dropping the exhaustiveness requirement — handler runs (on the full input type) when no case matched. Returns the result directly when data-first, or a reusable matcher when curried.

otherwise(handler: (input: T) => R): HasInput extends true ? R : (input: T) => R

Parameters

ParameterTypeDescription
handler(input: T) => R- fallback run on the input when no prior case matched

Returns

the result (data-first) or a matcher function (curried)

Example

type Event =
  | { type: "message"; content: string }
  | { type: "error"; message: string }
  | { type: "done" };

const len = match({ type: "done" } as Event)
  .with({ type: "message" }, (e) => e.content.length)
  .otherwise(() => -1); // -1

matchTag ƒ

Exhaustive match on _tag — for @onrails/result / @onrails/maybe style unions. The handlers object must supply one branch per _tag, and each handler receives the member narrowed to its tag.

function matchTag<T extends Tagged, Hs extends TagHandlers<T>>(value: T, handlers: Hs & { [K in Exclude<keyof Hs, T["_tag"]>]: never; }): HandlerResult<Hs>

Parameters

ParameterTypeDescription
valueT- a tagged union value to dispatch on
handlersHs & { [K in Exclude<keyof Hs, T["_tag"]>]: never; }- one handler per _tag, keyed by tag

Returns

the result of the matched handler

Example

import { err, ok, type Result } from "@onrails/result";

const label = (r: Result<number, string>) =>
  matchTag(r, {
    Ok:  (v) => `ok:${v.value}`,  // v: Ok<number>
    Err: (e) => `err:${e.error}`, // e: Err<string>
  });
label(ok(1));    // "ok:1"
label(err("x")); // "err:x"

when ƒ

Guard pattern for match.with.

Accepts plain boolean guards ((x) => x.length > 0) or TS type-predicate guards ((x): x is Foo => ...). For type predicates, the matched handler's input is narrowed to the predicate's target type via Narrow.

Note: a plain boolean guard does not advance exhaustiveness tracking — pair it with .otherwise(), or use a type predicate to narrow the union.

function when<T, U extends T>(guard: (input: T) => input is U): (input: T) => input is U
function when<T>(guard: (input: T) => boolean): Pattern<T>

Parameters

ParameterTypeDescription
guard(input: T) => input is U- boolean or type-predicate guard function

Returns

the guard, usable as a Pattern in .with

Example

const sign = match<number>()
  .with(when((n: number) => n < 0), () => "neg")
  .with(when((n: number) => n >= 0), () => "non-neg")
  .exhaustive();
sign(-1); // "neg"
sign(0);  // "non-neg"

Diagnostics

assertNever ƒ

Use in default branches (or after manual narrowing) to assert a union has been fully handled. If every case is handled, value is never and the call type-checks; an unhandled case makes value non-never, surfacing a compile error. Always throws at runtime.

function assertNever(value: never, message?: string): never

Parameters

ParameterTypeDescription
valuenever- the value that should be unreachable (typed never)
messagestring- error message prefix; defaults to "Unreachable"

Example

type Shape = { kind: "circle"; r: number } | { kind: "square"; s: number };

function area(shape: Shape): number {
  switch (shape.kind) {
    case "circle": return Math.PI * shape.r ** 2;
    case "square": return shape.s ** 2;
    default: return assertNever(shape); // type error if a case is added
  }
}

NonExhaustiveError type

Returned by .exhaustive() when union cases are still missing (compile-time error).

export type NonExhaustiveError<Remaining> = {
  readonly __nonExhaustive: "Add .with() branches for remaining cases";
  readonly remaining: Remaining;
};

Types

ExhaustiveResult type

.exhaustive() return type — NonExhaustiveError when cases are missing.

export type ExhaustiveResult<T, Handled extends readonly unknown[], R, HasInput extends boolean> =
  IsExhaustive<T, Handled> extends true
    ? ExhaustiveOutput<R, HasInput, T>
    : NonExhaustiveError<RemainingCases<T, Handled>>;

ExhaustMatched type

Union members of T ruled out by pattern P. Boolean guards (non-predicates) do not advance exhaustiveness — use when(isX) or .otherwise().

export type ExhaustMatched<T, P> = P extends (input: T) => boolean
  ? [GuardTarget<P>] extends [never]
    ? never
    : Extract<T, GuardTarget<P>>
  : Extract<T, P>;

HandledUnion type

Union of cases already handled by prior branches.

export type HandledUnion<Handled extends readonly unknown[]> = Handled[number];

IsExhaustive type

true when every member of T appears in Handled, otherwise false.

export type IsExhaustive<T, Handled extends readonly unknown[]> = [
  RemainingCases<T, Handled>,
] extends [never]
  ? true
  : false;

Narrow type

Narrows input when pattern is a shallow object, literal discriminant, or type predicate.

export type Narrow<T, P> = P extends (input: T) => boolean
  ? [GuardTarget<P>] extends [never]
    ? T
    : NarrowObject<T, GuardTarget<P>>
  : P extends Record<string, unknown>
    ? NarrowObject<T, P>
    : T extends P
      ? Extract<T, P>
      : T;

NarrowUnion type

Union of members narrowed by each pattern in Ps (multi-branch handlers).

export type NarrowUnion<T, Ps extends readonly unknown[]> = Narrow<T, Ps[number]>;

Pattern type

A pattern that matches a value of type T. One of:

  • Literal — a primitive ("a", 42, true) matched by ===.
  • Object pattern — a Partial<T> of shallow key/value pairs that must all match by strict equality. Only available when T is an object type.
  • Guard — a function (input: T) => boolean. Type predicates ((x): x is U) narrow the handler input via Narrow.
export type Pattern<T> = T | ObjectPattern<T> | PatternGuard<T>;

Example

type Event = { kind: "click"; x: number; y: number } | { kind: "key"; code: string };

const p1: Pattern<Event> = { kind: "click" };         // object pattern
const p2: Pattern<Event> = (e) => e.kind === "key";   // guard

RemainingCases type

Input cases not yet covered by .with / .withOneOf / .withEither.

export type RemainingCases<T, Handled extends readonly unknown[]> = Exclude<
  T,
  HandledUnion<Handled>
>;

On this page