TS-Pattern adds type-safe pattern matching to TypeScript with inference and exhaustiveness checking. It helps branch on complex data instead of nested conditionals.
Overview
TS-Pattern lets developers express branching logic with a match API similar to functional languages, covering nested objects, arrays, tuples, sets, maps, and primitives. Patterns include wildcards, predicates, unions, intersections, and exclusions, plus helpers such as P.select for pulling values into handlers.
The match builder chains with clauses, optional guards, return type enforcement, and terminators like exhaustive, otherwise, or run. Exhaustiveness checking warns when a union case is missing; otherwise supplies a catch-all. The isMatching helper validates values against patterns as a type guard.
Install via npm or another package manager and import into application code. Documentation covers reducers, event handling, and validation examples. Pattern matching is not yet a native JavaScript feature; this library implements the technique in userland with TypeScript types.
Compared with long if/else or switch trees, the API aims for shorter, readable expressions when state and events combine, such as frontend reducers that depend on both current state and incoming events.
Key features
- match, with, when, and otherwise API
- Compile-time exhaustiveness checking
- Wildcards and typed P.string helpers
- Predicates and P.not patterns
- P.select for nested data
- isMatching type guards
- Unions, intersections, exclusions
- Inference for input and output types
Use cases
- State reducers with typed events
- Replacing nested switch logic
- Runtime shape validation
- Exhaustive union handling
- Readable conditional branching