gpt4 book ai didi

javascript - 显式类型 - 对象数组

转载 作者:行者123 更新时间:2023-11-28 14:35:07 26 4
gpt4 key购买 nike

在下面的语法中,

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 是一个键:值对数组,其中键的类型为 string,值的类型为 IPerson

编辑:

下面的语法允许在数组的索引处有多个键:值对

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

如何显式键入 personList

最佳答案

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

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

关于javascript - 显式类型 - 对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50065354/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com