Reputation: 12015
I have custom interface type:
export interface IDictionary {
id: number;
dbVersion: number;
code: string;
tableName: string;
name: Name;
shortName: ShortName;
active: boolean;
restricted: boolean;
hierarchy: boolean;
metadata: string;
rights: any[];
}
And I tried to build Map():
dataMap = new Map<IDictionary, IDictionary[]>([
[{ name: { ru: "Root1"}} as IDictionary, [{ name: { ru: "Papa"}} as IDictionary]]
]);
Is it possible to use key
as IDictionary
type?
Then I try to get values by key:
this.dataMap.get(node);
Where node is object:
{ name: { ru: "Root1"}}
I should get: [{ name: { ru: "Papa"}}]
Upvotes: 0
Views: 106
Reputation: 11930
In JavaScript (and as an extension, TypeScript), no two objects are equal except if they refer to the same object. If you create a new object, it would not consider it to be equal to any existing one.
Because Maps consider such equality when looking up elements, if you store a value with an object as a key, you can only get the value out again if you pass in the exact same object reference as a key again:
interface Name {
ru: string
}
interface ShortName extends Name {}
interface IDictionary {
id?: number;
dbVersion?: number;
code?: string;
tableName?: string;
name: Name;
shortName?: ShortName;
active?: boolean;
restricted?: boolean;
hierarchy?: boolean;
metadata?: string;
rights?: any[];
}
const node = { name: { ru: 'Root1' } }
const dataMap = new Map<IDictionary, IDictionary[]>([[
node, [{ name: { ru: 'Papa' } }]
]])
console.log(dataMap.get({ name: { ru: 'Root1' } })) // undefined
console.log(dataMap.get(node)) // [ { name: { ru: 'Papa' } } ]
Upvotes: 4