ts-pattern is an open-source TypeScript library that introduces expressive, type-safe pattern matching for handling complex conditional logic. It allows developers to replace lengthy switch statements and nested conditionals with concise declarative expressions. The library supports matching primitive values, nested objects, arrays, tuples, maps, and sets. Its advanced TypeScript inference automatically narrows types based on matched patterns, reducing the need for manual assertions. Exhaustiveness checking detects unhandled cases during compilation and helps prevent unexpected application behavior. Developers can create conditional patterns using predicates, unions, intersections, exclusions, and wildcard matchers. It also supports extracting matched values and validating data structures. With a small bundle footprint, ts-pattern integrates into existing TypeScript applications without requiring additional runtime infrastructure.
Features
- Type-Safe Declarative Pattern Matching
- Compile-Time Exhaustiveness Checking
- Nested Object and Array Matching
- Advanced Type Inference and Narrowing
- Wildcard, Predicate, and Union Patterns
- Data Validation and Value Extraction