[英]Object.keys - Element has type "any" implicitly in Typescript
I have a function to obtain the key having the value of the property.我有一个 function 来获取具有属性值的键。 When replicating this function in Typescript I get the following error:在 Typescript 中复制此 function 时出现以下错误:
The element implicitly has type "any" because the expression of type "any" cannot be used to index the type "TestModel"
This is my function:这是我的 function:
interface TestModel {
test: string,
"test 1": string,
data: string,
"data 1": string
}
getKeyByValue(value: string) {
let data: TestModel = {
test: "test",
"test 1": "one Test",
data: "data",
"data 1": "one data"
}
return Object.keys(data).find((key: any) => data[key] === value);
}
UPDATE更新
New function:新 function:
return Object.keys(data).find((key: string) => data[key] === value);
Error:错误:
let data: TestModel
The element implicitly has type "any" because the expression of type "string" cannot be used to index the type "TestModel".
No index signature found with a parameter of type "string" on type "TestModel"
There is no need to use explicit any
type for key.无需为密钥使用显式any
类型。 TS is able to figure out that type of key
is string. TS 能够判断出该类型的key
是字符串。 However, we know that type of key
is keyof TestModel
.但是,我们知道key
的类型是keyof TestModel
。
Object.keys
always returns string[]
instead of keyof T
- this is by design, for safety reasons. Object.keys
总是返回string[]
而不是keyof T
- 这是设计使然,出于安全原因。 Hence the most common way in typescript is to use type assertion
in this case:因此 typescript 中最常见的方法是在这种情况下使用type assertion
:
interface TestModel {
test: string,
"test 1": string,
data: string,
"data 1": string
}
class Foo {
getKeyByValue(value: string) {
let data: TestModel = {
test: "test",
"test 1": "one Test",
data: "data",
"data 1": "one data"
}
return (
(Object.keys(data) as Array<keyof TestModel>)
.find((key) => data[key] === value)
);
}
}
You can find more information in my article您可以在我的文章中找到更多信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.