【问题标题】:how to declare and create dictionary with object as key如何声明和创建以对象为键的字典
【发布时间】:2020-01-21 09:09:58
【问题描述】:

我正在尝试创建一个打字稿字典,其键是具有 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中只能是字符串,在Typescript中也是如此。
  • @RemcoGerlich 也可以是数字 {1:1} 是有效对象
  • @JurajKocan: 只是因为 JS 将数字转换为字符串,x = {1: "A", "1": "B"} 使 x 成为具有 1 个元素的对象。
  • @RemcoGerlich x = {"1": "A", 1: "B"} 使 x 为 {1: "B"}...我不想和你争论,只是兴趣

标签: angular typescript ecmascript-5


【解决方案1】:

不要使用普通的 javascript 对象作为字典,而是使用 MapMap 可以使用任何对象作为键:new Map&lt;IMyDictionaryKey, any&gt;。特别是有一个WeakMap,重点讲对象作为key的使用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-25
    • 1970-01-01
    • 1970-01-01
    • 2019-05-02
    • 2016-05-14
    • 1970-01-01
    • 2021-11-26
    相关资源
    最近更新 更多