Registry / serialization / ts-pattern

ts-pattern

JSON →
library5.9.0jsnpmunverified

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-pattern
INSTALL
IMPORT
SIG · TS-PATTERN
T
ts-pattern
serializationjavascriptv5.9.0
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

match
import { match } from 'ts-pattern';
const match = require('ts-pattern').match;
TS-Pattern is primarily consumed as an ESM module. CommonJS `require` syntax is not idiomatic and might lead to type inference issues in newer TypeScript projects.
P
import { P } from 'ts-pattern';
import * as P from 'ts-pattern';
The 'P' object is a namespace containing various pattern utilities (wildcards, predicates, etc.). It should be imported directly as a named import, not as a default or star import.
isMatching
import { isMatching } from 'ts-pattern';
Used for validating the shape of data against a pattern. Available as a named export.

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.

import { match, P } from 'ts-pattern'; type UserRole = 'admin' | 'editor' | 'viewer'; type UserProfile = | { role: 'admin'; permissions: string[]; department: string } | { role: 'editor'; projects: string[]; lastLogin: Date } | { role: 'viewer'; lastViewed: string; theme: 'dark' | 'light' }; const getUserDashboardContent = (user: UserProfile): string => { return match(user) .with({ role: 'admin', department: P.select('dept') }, ({ dept }) => `Welcome Admin! You manage the ${dept} department.` ) .with({ role: 'editor', projects: P.array(P.string) }, (editor) => `Hello Editor! Your active projects are: ${editor.projects.join(', ')}.` ) .with({ role: 'viewer', theme: 'dark' }, () => `Viewer mode: Enjoy your dark theme.` ) .with({ role: 'viewer', theme: 'light' }, () => `Viewer mode: Enjoy your light theme.` ) .exhaustive(); }; const adminUser: UserProfile = { role: 'admin', permissions: ['full'], department: 'IT' }; const editorUser: UserProfile = { role: 'editor', projects: ['Project Alpha', 'Project Beta'], lastLogin: new Date() }; const viewerUserDark: UserProfile = { role: 'viewer', lastViewed: 'docs', theme: 'dark' }; console.log(getUserDashboardContent(adminUser)); console.log(getUserDashboardContent(editorUser)); console.log(getUserDashboardContent(viewerUserDark));
Debug
Known issues
breakingSymbol keys are now considered in object patterns. Previously, symbol keys in objects were ignored during pattern matching, meaning `isMatching({ [symbolA]: 'bar' }, obj)` would incorrectly return true if `obj` was `{ [symbolA]: 'foo' }` (matching the empty object part).
fix
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.
affects: >=5.3.1
breakingWhen using `isMatching` with two parameters (pattern and value), the pattern now undergoes type-checking against the value's type. This prevents passing patterns that could never match the provided value.
fix
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.
affects: >=5.6.0
gotchaThe `.exhaustive()` method, by default, throws an error if no `with` clause matches the input value. While this indicates a type inconsistency, in rare scenarios, you might want to customize this behavior.
fix
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); });`
affects: >=5.7.0
gotchaWhen working with deeply nested union types or nullable properties, TypeScript's inference might not always narrow types as aggressively as desired within complex pattern matching scenarios.
fix
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.
affects: >=5.8.0
Errors
Common errors & fixes
Argument of type '{ type: "one"; } | { type: "two"; }' is not assignable to parameter of type 'never'.
This error typically occurs when the `.exhaustive()` method cannot confirm that all possible cases of the input type have been handled by the preceding `.with()` or `.otherwise()` clauses, meaning some branches are implicitly 'never' reached by the patterns.
fix
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.
Type '{ type: "someType"; }' is not assignable to type 'P.Pattern<T>'
This usually indicates a type mismatch between the expected input type of the `match` function and the pattern being provided in a `.with()` clause. The pattern you're trying to match is incompatible with the type `T` of the `match` input.
fix
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.
TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.
This is a general TypeScript error that can arise if a `P.select()` pattern extracts a value with an unexpected type, or a callback function within `.with()` receives arguments of types that don't match its signature.
fix
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`.
Upgrade
Version history
5.9.0latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
5 hits · last 30 days
node
4
OpenAI (training)
1
Resources
ts-pattern — npm install ts-pattern · libregistry