v5.9.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.
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:
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"