我有一個函式來獲取具有屬性值的鍵。在 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"
uj5u.com熱心網友回復:
不需要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)
);
}
}
您可以在我的文章中找到更多資訊
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/485967.html
上一篇:動態重命名物件中的鍵/值
