Download Latest Version v5.9.2 source code.zip (323.1 kB) Google Add to Preferred Sources
Home / v5.9.0
Name Modified Size InfoDownloads / Week
Parent folder
README.md 2025-10-26 2.6 kB
v5.9.0 source code.tar.gz 2025-10-26 266.5 kB
v5.9.0 source code.zip 2025-10-26 303.0 kB
Totals: 3 Items   572.0 kB 0

New features

P.record patterns

To match a Record<Key, Value> (an object with consistent key and value types), you can use P.record(keyPattern, valuePattern). It takes a sub-pattern to match against the key, a sub-pattern to match against the value, and will match if all entries in the object match these two sub-patterns.

:::ts
import { match, P } from 'ts-pattern';

type Input = Record<string, number>;

const input: Input = {
  alice: 100,
  bob: 85,
  charlie: 92,
};

const output = match(input)
  .with(P.record(P.string, P.number), (scores) => `All user scores`)
  .with(P.record(P.string, P.string), (names) => `All user names`)
  .otherwise(() => '');

console.log(output);
// => "All user scores"

You can also use P.record with a single argument P.record(valuePattern), which assumes string keys:

:::ts
const userProfiles = {
  alice: { name: 'Alice', age: 25 },
  bob: { name: 'Bob', age: 30 },
};

const output = match(userProfiles)
  .with(
    P.record({ name: P.string, age: P.number }),
    (profiles) => `User profiles with name and age`
  )
  .otherwise(() => 'Different format');

console.log(output);
// => "User profiles with name and age"

When using P.select in record patterns, you can extract all keys or all values as arrays:

:::ts
const data = { a: 1, b: 2, c: 3 };

const keys = match(data)
  .with(P.record(P.string.select(), P.number), (keys) => keys)
  .otherwise(() => []);

const values = match(data)
  .with(P.record(P.string, P.number.select()), (values) => values)
  .otherwise(() => []);

console.log(keys); // => ['a', 'b', 'c']
console.log(values); // => [1, 2, 3]

What's Changed

New Contributors

Full Changelog: https://github.com/gvergnaud/ts-pattern/compare/v5.8.0...v5.9.0

Source: README.md, updated 2025-10-26