Object.keys - 元素在 Typescript 中隐式具有类型 "any"
Object.keys - Element has type "any" implicitly in Typescript
我有一个函数可以获取具有 属性 值的键。在 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
总是 returns 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)
);
}
}
您可以在 my article
中找到更多信息
我有一个函数可以获取具有 属性 值的键。在 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
总是 returns 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)
);
}
}
您可以在 my article
中找到更多信息