Collections
Map: オブジェクトキーはプロパティではなく参照で照合する
同じプロパティを持つ別オブジェクトは、Map の同じキーとして検索されません。
SourceobjectMapKeys.ts
Node.js 22
export type Key = { id: string };
export function valueFor(map: Map<Key, string>, key: Key): string | undefined {
return map.get(key);
}TestobjectMapKeys.test.ts
Node.js 22
import assert from "node:assert/strict";
import test from "node:test";
import { valueFor } from "../../src/map/objectMapKeys.js";
test("同じIDを持つ別オブジェクトではMapを検索できない", () => {
const stored = { id: "a" };
const map = new Map([[stored, "value"]]);
assert.equal(valueFor(map, stored), "value");
assert.equal(valueFor(map, { id: "a" }), undefined);
});01Assertion
このテストで確認できること
- 登録に使った同一オブジェクトでは検索できる
- 同じプロパティを持つ別オブジェクトでは検索できない
Map の object key は参照同一性を用います。キーに値としての意味が必要なら string や number の ID を使います。
OBSERVED RESULT
expected: map.get({id:"a"}) → undefined
actual: undefined