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

问题描述 投票:0回答:1

我正在尝试创建一个打字稿字典,它的键是具有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];
angular typescript ecmascript-5
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.