如何声明和创建以对象为键的字典



我正在尝试创建一个打字稿字典,它的键是一个具有 2 个属性的对象:

我尝试为密钥使用接口:

/*
export interface IMyDictionary<TValue>
{
[{ property1 : string, property2: number}] : TValue  //or 
[IMyDictionaryKey] : TValue // none of them works
}
*/
export interface IMyDictionaryKey
{
property1 : string;
property2 : number
}
export class MyDictionaryKey implements IMyDictionaryKey
{
property1 : string;
property2 : number;
constructor(prop1: string, prop2 : number)
{
property1 = prop1;
property2 : prop2;
}
}

在组件本身中,我想做这样的事情:

Mydictionary : IMyDictionary<number[]>; //OR 
Mydictionary : {} = {};

并设置新的键值项:

this.Mydictionary[new MyDictionaryKey("AAAA", 1) as IMyDictionaryKey] = [];

然后将值数组作为该键的值插入:

this.Mydictionary[{ property1: "AAAA", property2: 1}] = [1,2,3,4];

不要使用普通的javascript对象作为字典,而是使用Map。Map可以使用任何对象作为键:new Map<IMyDictionaryKey, any>。特别是,有一个WeakMap,它专注于使用对象作为键。

最新更新