@lebedevna/match
v0.1.0
Published
Tiny TypeScript helpers for exhaustive matching on string unions.
Readme
@lebedevna/match
Tiny TypeScript helpers for exhaustive matching on string unions.
@lebedevna/match gives you two small utilities:
matchfor mapping a string union to a valuematchffor mapping a string union to a function and executing only the selected branch
The API is intentionally minimal. It uses TypeScript's type system to require a case for every member of the union.
Install
npm install @lebedevna/matchUsage
match
Use match when each branch returns a plain value.
import { match } from "@lebedevna/match";
type Status = "idle" | "loading" | "success" | "error";
const status: Status = "success";
const label = match(status, {
"idle": "Idle",
"loading": "Loading...",
"success": "Done",
"error": "Failed",
});Because the second argument is Record<T, TValue>, TypeScript requires every possible key from T.
type Theme = "light" | "dark";
const className = match<Theme, string>("light", {
"light": "theme-light",
"dark": "theme-dark",
});matchf
Use matchf when branch logic should run lazily.
import { matchf } from "@lebedevna/match";
type Role = "guest" | "user" | "admin";
const role: Role = "admin";
const permissions = matchf(role, {
"guest": () => ["read"],
"user": () => ["read", "comment"],
"admin": () => ["read", "comment", "write", "delete"],
});This is useful when branches are expensive, have side effects, or are easier to express as separate functions.
Why use this
- Exhaustive by type: missing cases fail at compile time
- Tiny surface area: two functions, no DSL
- Works well with string literal unions
matchfavoids evaluating unused branches
API
function match<T extends string, TValue>(
value: T,
variants: Record<T, TValue>,
): TValue;
function matchf<T extends string, TValue>(
value: T,
variants: Record<T, () => TValue>,
): TValue;Notes
valuemust be typed as a string literal union for exhaustive checking to be useful- The helpers do not provide a fallback branch; every case must be present
- These helpers are designed for TypeScript, not runtime validation of arbitrary input
License
MIT
