我的数据具有以下结构:
groups = {
someGroupName: {
total: 30,
count: 3,
average: 10
},
someOtherGroupName: {
total: 60,
count: 3,
average: 20
}
}
我可以为嵌套部分编写一个接口:
interface Stats {
total: number,
count: number,
average: number
}
但是如何为整个组设置类型?我不知道要加入哪些组。我只知道它将以组名作为键,而将统计对象作为值。
答案 0 :(得分:2)
您可以使用索引签名来告诉Typescript该对象可被任何字符串索引,但是该对象中的所有值均为特定类型:
interface Stats {
total: number,
count: number,
average: number
}
interface Groups {
[name: string] : Stats
}
let groups: Groups = {
someGroupName: {
total: 30,
count: 3,
average: 10
},
someOtherGroupName: {
total: 60,
count: 3,
average: 20
}
}
let someGroupName = groups['someGroupName'] //someGroup is Stats
groups['someGroupName'] = 0 // invalid 0 is not of type Stats