我有一个函数来获取具有属性值的键。在 Typescript 中复制此函数时,出现以下错误:
The element implicitly has type "any" because the expression of type "any" cannot be used to index the type "TestModel"
这是我的功能:
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);
}
更新
新功能:
return Object.keys(data).find((key: string) => data[key] === value);
错误:
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"
不需要any
对键使用显式类型。TS 能够找出key
字符串的类型。但是,我们知道类型key
是keyof TestModel
。
Object.keys
总是返回string[]
而不是keyof T
- 出于安全原因,这是设计使然。因此,打字稿中最常见的方法是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)
);
}
}
您可以在我的文章中找到更多信息
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句