您可以使用索引签名告诉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