如何在打字稿中创建词典列表?

时间:2020-05-05 15:04:44

标签: typescript

直觉上,人们会尝试类似的事情:

interface Port_Mapping {
  number: Port_role
}
port_mappings: Port_Mapping[{number: Port_role}] = [];

其中Port_role是接口,数字是整数键。但这是满足的:

输入'{number:Port_role; }'不能用作索引类型。

然后可能会尝试更改为:

interface Port_Mapping {
  number: Port_role
}

port_mappings: Port_Mapping[] = [];

this.port_mappings.push({5: Port_role.input})

但是这也不起作用,因为接口中的数字实际上是名称而不是类型,并且您最终得到:

类型'{5的参数:Port_role; }'不可分配给的参数 输入“ Port_Mapping”。对象文字只能指定已知 属性,并且'Port_Mapping'类型中不存在'5'。

在我的情况下,我想要一个字典列表,其中每个字典的形式为:

[{key1: value1, key2: value2, key3: value3}]

2 个答案:

答案 0 :(得分:2)

尝试

interface Port_Mapping {
  [index: number]: Port_role
}

[index:number]是一个索引器-只能在接口中使用,这意味着您可以使用它对对象实例进行索引。

您的第一次尝试在TS中没有多大意义,您声明变量port_mappings的类型为Port_Mapping,并以对象实例{number: Port_role}进行索引,其中number属性是接口类型Port_role

在第二次尝试中,您尝试将对象实例{5: Port_role.input}推入类型Port_Mapping的数组中。在那里,您会看到一个明显的类型不匹配,因为您要推送的对象实例没有number属性(并且您要推送到的数组类型(Port_Mapping)没有名为“ 5”的属性)。 / p>

用法:

interface Dict {
  [idx: number]: string
}

const i = 5;
const dict: Dict = { 1: 'abc', [2]: 'def', [i]: 'ghi' };
dict[7] = 'jkl';
dict[i] = 'mno';
delete dict[2]; // removes the index 2: 'def' entry

const listOfDict: Dict[] = [dict, { 1: 'a', [2]: 'b', [i]: 'c'}];
listOfDict.push({ 1: 'a', [2]: 'b', [i]: 'c'});

答案 1 :(得分:0)