TS-Pattern is an exhaustive pattern matching library for TypeScript, providing a typesafe and highly ergonomic API to handle complex conditional logic. It is currently at version 5.9.0 and receives regular updates, often including new pattern types, performance improvements, and type inference enhancements. Key differentiators include its extensive support for various data structures (objects, arrays, tuples, sets, maps, primitives), robust type inference, and crucial exhaustiveness checking, ensuring all possible cases are handled at compile-time. It aims to provide a user-land implementation of pattern matching, similar to those found in functional languages, anticipating a future TC39 proposal, while maintaining a tiny bundle footprint of around 2kB.
npm install ts-patternVerified import paths — ran on the pinned version, not inferred.
This example demonstrates pattern matching on a discriminated union `UserProfile` using `match` and `P.select` for extracting values, `P.array` for matching array types, and `exhaustive` to ensure all cases are handled, returning a personalized dashboard message.
Review object patterns involving Symbol keys to ensure they explicitly match the desired Symbol values. If you previously relied on symbols being ignored, you might need to adjust your patterns or input data.
Ensure that the pattern provided to `isMatching` is compatible with the type of the value it's being compared against. Correct any type mismatches in the pattern definition.
You can pass a custom handler function to `.exhaustive()` to define what should happen when an unexpected value is received. For example, `match(...).with(...).exhaustive((unexpected: unknown) => { throw new MyCustomError(unexpected); });`Utilize the `.narrow()` method after a `with` clause to explicitly narrow the input type for subsequent patterns, excluding values already handled. This gives more fine-grained control over deep type narrowing.
Add a `.with()` clause for any missing cases or use an `.otherwise(() => ...)` clause as a fallback. For deeply nested types, ensure type guards are precise or use `.narrow()` to guide inference.
Review your input type `T` for `match` and ensure your patterns accurately reflect the possible shapes within `T`. This might involve refining discriminated unions or correcting object structures.
Inspect the `P.select()` pattern to confirm it extracts the expected type. Also, verify the type signature of your callback function in `.with()` to ensure it correctly handles the types inferred by `ts-pattern`.
No dependency data recorded yet.