【发布时间】: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