Create a type-safe exhaustive match for union types
type Status = "pending" | "success" | "error"
const status: Status = "success"
const result = Match.exhaustive<Status, string>({
pending: "Waiting...",
success: "Done!",
error: "Failed!"
})(status)
// result = "Done!"
// For function values, wrap in object to prevent execution
type Operation = "add" | "subtract" | "multiply"
const ops = Match.exhaustive<Operation, { fn: (a: number, b: number) => number }>({
add: { fn: (a, b) => a + b },
subtract: { fn: (a, b) => a - b },
multiply: { fn: (a, b) => a * b }
})
const compute = ops("multiply").fn
const result = compute(4, 5) // 20
Create a partial match that requires a default
Pattern match with guards
const score = 85
const grade = Match.withGuards<number, string>([
[n => n >= 90, "A"],
[n => n >= 80, "B"],
[n => n >= 70, "C"],
[n => n >= 60, "D"]
]).withDefault("F")(score)
// grade = "B"
// With function results for custom messages
const age = 25
const category = Match.withGuards<number, string>([
[n => n < 13, n => `Child (${n} years)`],
[n => n < 20, n => `Teenager (${n} years)`],
[n => n < 60, n => `Adult (${n} years)`],
[n => n >= 60, n => `Senior (${n} years)`]
]).withDefault("Unknown")(age)
// category = "Adult (25 years)"
// Basic pattern matching
const result = Match(value)
.case(x => x > 0, "positive")
.case(x => x < 0, "negative")
.default("zero")
Pattern matching utility for type-safe conditional logic