[英]typescript type object with string keys and content defined by interface
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.
我不知道进入的是哪些组。我只知道它将以组名作为键,以 stats 对象作为值。
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: 您可以使用索引签名来告诉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
You can use {[key:string]:string}
as a type for any object with string values and string keys.您可以使用
{[key:string]:string}
作为具有字符串值和字符串键的任何对象的类型。
type strObj = {[key:string]:string}
const sample:strObj = {
one:"text1",
two:"text2"
}
For nested Object对于嵌套对象
And if it is a nested object, you can nest the type in place of string at the end.如果它是嵌套对象,则可以在末尾嵌套类型代替字符串。
{[key:string]:
string
}
==> {[key:string]: {[key:string]:string}}
{[key:string]:
string
}
==> {[key:string]: {[key:string]:string}}
Hence,因此,
type strObj = {[key:string]:{[key:string]:string}}
const sample:strObj = {
one:{
sub:"text1"
},
two:{
sub:"text2"
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.