TypeScript Pattern Matching Approaches
JavaScript lacks native pattern matching, but TypeScript’s type system lets us approximate it in several ways.
Discriminated Unions
type Shape =
| { kind: "circle"; radius: number }
| { kind: "rect"; width: number; height: number }
| { kind: "triangle"; base: number; height: number };
function area(s: Shape): number {
switch (s.kind) {
case "circle": return Math.PI * s.radius ** 2;
case "rect": return s.width * s.height;
case "triangle": return (s.base * s.height) / 2;
}
}
Exhaustive Checking
Use never to ensure all cases are handled:
function assertNever(x: never): never {
throw new Error(`Unexpected case: ${x}`);
}
function area(s: Shape): number {
switch (s.kind) {
case "circle": return Math.PI * s.radius ** 2;
case "rect": return s.width * s.height;
case "triangle": return (s.base * s.height) / 2;
default: return assertNever(s);
}
}
Adding a new variant to Shape will now produce a compile error
until every switch is updated — a small discipline that prevents
large runtime surprises.