问题描述
我是新手,正在学习 Typescript 并在我的项目中并行实现。我用打字稿写的类如下:
class Base {
property1!: number
property2!: string
getValue(field: string) {
const exists = Object.prototype.hasOwnProperty.call(this,field)
const value = this[field]
const isNotFunction = value !== 'function'
return exists && isNotFunction && field !== 'id' && field !== 'type'
}
}
现在 tsc
命令给出了以下错误,我不太理解。请帮忙。
src/models/base.ts - error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Base'.
No index signature with a parameter of type 'string' was found on type 'Base'.
137 const value = this[field]
解决方法
您的类 Base
具有一组预定义的属性(property1
和 property2
)。 Typescript 意识到这一点,因此当您尝试通过随机字符串名称(即 Base
)访问 field: string
的属性时,它告诉您您可能正在做一些您不应该做的事情。尝试将其更改为 field: keyof Base
- 这样您就可以确保该属性实际存在于对象实例上,并且您得到的是合理的类型化结果,而不是 any