matches() function
指定されたパターンのすべてのプロパティに一致するかどうかを確認する述語(predicate)関数を生成します。
ネストされたオブジェクトと配列に対して深い比較を行います。 find、filter、some、every でコールバック関数をオブジェクトパターンに置き換える際に便利です。
Signature:
typescript
function matches<T>(pattern: Record<Key, any>): (input: T) => boolean;Example
ts
const users = [
{ name: "John", age: 30, active: true },
{ name: "Jane", age: 25, active: false },
{ name: "Bob", age: 30, active: true },
];
// filterと一緒に使用
filter(matches({ age: 30, active: true }), users);
// [{ name: "John", age: 30, active: true }, { name: "Bob", age: 30, active: true }]
// findと一緒に使用
find(matches({ active: true }), users);
// { name: "John", age: 30, active: true }
// pipeと一緒に使用
pipe(users, filter(matches({ active: true })), toArray);
// [{ name: "John", age: 30, active: true }, { name: "Bob", age: 30, active: true }]
// ネストされたオブジェクトのマッチング
const data = [
{ id: 1, user: { profile: { age: 30 } } },
{ id: 2, user: { profile: { age: 25 } } },
{ id: 3, user: { profile: { age: 30 } } },
];
filter(matches({ user: { profile: { age: 30 } } }), data);
// [{ id: 1, user: { profile: { age: 30 } } }, { id: 3, user: { profile: { age: 30 } } }]
// 配列値のマッチング
const items = [
{ id: 1, tags: ["a", "b"] },
{ id: 2, tags: ["c", "d"] },
{ id: 3, tags: ["a", "b"] },
];
filter(matches({ tags: ["a", "b"] }), items);
// [{ id: 1, tags: ["a", "b"] }, { id: 3, tags: ["a", "b"] }]
// null/undefined 入力に対して false を返す
const matcher = matches({ a: 1 });
matcher(null); // false
matcher(undefined); // falseパターンの Symbol キーはランタイムで無視されます。 内部的に matches は Object.entries を使用してパターンのエントリを反復するため、 文字列キー(および数値キー)のプロパティのみが列挙されます。
ts
const sym = Symbol("id");
// matches({ [sym]: 123 });
// ~~~~
// Error: Type 'symbol' cannot be used as an index type.
// ランタイムでバイパスした場合、Symbolキーは無視されます:
const pattern = { [sym]: 123 } as any;
matches(pattern)({}); // true — Symbolキーは比較されなかった