@naamanu/tagu
v0.0.1
Published
Type-safe pattern matching for TypeScript discriminated unions
Maintainers
Readme
tagu
Type-safe pattern matching for TypeScript discriminated unions.
Installation
npm install @naamanu/taguUsage
import { match } from "@naamanu/tagu";
// Define a tagged union
type Result =
| { _tag: "Success"; data: string }
| { _tag: "Failure"; error: string };
const result: Result = { _tag: "Success", data: "Hello" };
// Match against it
const message = match(result)({
Success: ({ data }) => `Got: ${data}`,
Failure: ({ error }) => `Error: ${error}`,
});
console.log(message); // "Got: Hello"API
match<T>(value: T)
Pattern matches on a tagged union value. Returns a function that takes a pattern object with handlers for each variant.
type Shape =
| { _tag: "Circle"; radius: number }
| { _tag: "Rectangle"; width: number; height: number };
const shape: Shape = { _tag: "Circle", radius: 5 };
const area = match(shape)({
Circle: ({ radius }) => Math.PI * radius * radius,
Rectangle: ({ width, height }) => width * height,
});Pattern<T, R>
Type helper for defining pattern objects. Ensures exhaustive matching at compile time.
import { Pattern } from "@naamanu/tagu";
const pattern: Pattern<Shape, number> = {
Circle: ({ radius }) => Math.PI * radius * radius,
Rectangle: ({ width, height }) => width * height,
};Tag
Base type constraint for tagged union members. All variants must have a _tag string property.
License
MIT
