Create a pattern matcher with guards and nested patterns
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 matching for objects with specific structure
type Event =
| { type: "click"; x: number; y: number }
| { type: "keypress"; key: string }
| { type: "hover"; element: string }
const handler = Match.struct<Event, void>()
.case({ type: "click" }, (e) => console.log(`Click at ${e.x}, ${e.y}`))
.case({ type: "keypress", key: "Enter" }, () => console.log("Enter pressed"))
.case({ type: "hover" }, (e) => console.log(`Hovering over ${e.element}`))
.build()
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")
// Exhaustive matching for union types
type Color = "red" | "green" | "blue"
const hex = Match.exhaustive<Color, string>({
red: "#FF0000",
green: "#00FF00",
blue: "#0000FF"
})(color)
// Nested pattern matching
type User = { name: string; age: number; role: "admin" | "user" }
const user: User = { name: "John", age: 30, role: "admin" }
const message = Match<User, string>(user)
.case({ role: "admin", age: (n) => n >= 18 }, "Adult admin")
.case({ role: "user" }, u => `User: ${u.name}`)
.default("Unknown")
Pattern matching utility for type-safe conditional logic with exhaustiveness checking, nested patterns, and guard support