my data has this structure:
groups = {
someGroupName: {
total: 30,
count: 3,
average: 10
},
someOtherGroupName: {
total: 60,
count: 3,
average: 20
}
}
I can write an interface for the nested part:
interface Stats {
total: number,
count: number,
average: number
}
but how can I set a type for groups as a whole? I do not know what groups are coming in. I just know that it will be a groupname as the key and the stats object as the value.
You can use an index signature to tell typescript that the object is indexable by any string but all values in the object are of a certain type:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With