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"When using P.select in record patterns, you can extract all keys or all values as arrays:
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
- Fix: Add missing public/index.html to gif-fetcher example by @rio-sung-ks in #330
- set sideEffects to false to make ts-pattern tree shakable by @timvandam in #317
- feat(P.record): implementation by @gvergnaud in #332
New Contributors
- @rio-sung-ks made their first contribution in #330
- @timvandam made their first contribution in #317
Full Changelog: v5.8.0...v5.9.0