[英]Typescript get object value from key
How to get the property using the index of the key of an object in typescript?如何使用 typescript 中 object 的键的索引获取属性?
Despite the error on TypeScript, the code works correctly.尽管 TypeScript 出现错误,但代码可以正常工作。
My code我的代码
const payments = {
KEY1: {prop1: "prop1"},
KEY2: {prop1: "prop1"}
}
When I try to access by key value I got the error当我尝试通过键值访问时出现错误
const index = 0
const key = Object.keys(payments)[index]
const payment = payments[key] // ERROR HERE
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'.元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型“{}”。 No index signature with a parameter of type 'string' was found on type '{}'.ts(7053)在类型 '{}'.ts(7053) 上找不到具有类型参数的索引签名
payments
is of type object payments
类型为object
Add this添加这个
const key = Object.keys(payments)[index] as keyof typeof payments;
When you don't explicitly declare type for payments
, typescript inferred as specific keys( KEY1
and KEY2
)当您没有明确声明payments
类型时, typescript 被推断为特定键( KEY1
和KEY2
)
and Object.keys()
returns type as string that leads to error.和Object.keys()
将类型返回为导致错误的字符串。
The above line I modified will tell typescript that key
will be keys of payments and not string.我修改的上述行将告诉 typescript key
将是支付密钥而不是字符串。
You can read more about this here Creating Types from Types你可以在这里阅读更多关于这个从类型创建类型
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.