[英]Typescript - Type definition of object literal
I have an object like so - an int followed by a string, I tried setting the type like below, however it doesn't seem valid.我有一个像这样的 object - 一个 int 后跟一个字符串,我尝试像下面这样设置类型,但它似乎无效。 I guess it's something really simple I'm missing.
我想这是我想念的非常简单的东西。
const months: { int: string; } = {
0: 'JAN',
1: 'FEB',
2: 'MAR'
}
Update: I just found this works - correct?更新:我刚刚发现这行得通 - 对吗?
const months: { [number: number]: string } = { ... }
or is my only generic option to use:或者是我唯一可以使用的通用选项:
const months: any = {
0: 'JAN',
1: 'FEB',
2: 'MAR'
}
Thanks.谢谢。
What you're essentially saying is month is of type {int: string}
where the created objects must have int property of type string .你本质上说的是 month 的类型是
{int: string}
,其中创建的对象必须具有string类型的int属性。 As in,如中,
{
int: '1'
}
What you really want is a dictionary type and you'd create one like this.你真正想要的是一种字典类型,你会创建一个这样的。
const months: { [int: number]: string } =
{
0: 'JAN'
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.