显式类型 - 对象数组

时间:2018-04-27 15:09:13

标签: javascript typescript ecmascript-6

在下面的语法中,

interface IPerson{
    firstName: string;
    lastName?: string;
}

const personList = [
    "p1": {firstName: "F1", lastName: "L1"},
    "p2": {firstName: "F2"},
    "p3": {firstName: "F3"}
];

// or

const personList = [
    {"p1": {firstName: "F1", lastName: "L1"}},
    {"p2": {firstName: "F2"}},
    {"p3": {firstName: "F3"}}
];

personList是一个key:value对数组,其中key的类型为string,value的类型为IPerson

修改

以下语法允许在数组的索引处使用多个键:值对

const personList:{[key:string]:IPerson}[] = [
    {
     "p1": {firstName: "F1", lastName: "L1"},
     "p2": {firstName: "F1", lastName: "L1"}   
    },
    {"p2": {firstName: "F2"}},
    {"p3": {firstName: "F3"}}
];

如何明确键入personList

3 个答案:

答案 0 :(得分:3)

const personList: { [key: string]: IPerson }[]  = [
    {"p1": {firstName: "F1", lastName: "L1"}},
    {"p2": {firstName: "F2"}},
    {"p3": {firstName: "F3"}}
];

将其定义为一个对象数组,其键是一个字符串,其值为IPerson

答案 1 :(得分:1)

索引类型不能限制为单个属性,因此发布的答案都可能与您获得的答案一样好。

作为替代方案,您可以使用tuple type

const personList: [string, IPerson][] = [
    ["p1", { firstName: "F1", lastName: "L1" }],
    ["p2", { firstName: "F2"}],
    ["p3", { firstName: "F3" }]
];

这会将数组的每个元素约束为[string, IPerson]

的数组
personList.forEach(item => {
    const [key, person] = item;
    // `key` is type string (p1, p2, p3...)
    // `person` is type IPerson
});

答案 2 :(得分:0)

您可以创建地图界面:

interface Map<T> {
    [K: string]: T;
}

const personList: Map<IPerson> = [];