从 class 动态读取值导致打字稿错误
Reading values from class dynamically leading to typescript error
我是新手,在我的项目中学习 Typescript 和并行实现。我有 class 的打字稿如下:
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]
您的 class Base
具有一组预定义的属性(property1
和 property2
)。 Typescript 知道这一点,所以当您尝试通过随机字符串名称(即 field: string
)访问 属性 of Base
时,它告诉您您可能正在做一些您应该做的事情't。尝试将其更改为 field: keyof Base
- 这样您可以确保 属性 实际上存在于对象实例上,并且您将获得合理的类型化结果而不是 any
我是新手,在我的项目中学习 Typescript 和并行实现。我有 class 的打字稿如下:
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]
您的 class Base
具有一组预定义的属性(property1
和 property2
)。 Typescript 知道这一点,所以当您尝试通过随机字符串名称(即 field: string
)访问 属性 of Base
时,它告诉您您可能正在做一些您应该做的事情't。尝试将其更改为 field: keyof Base
- 这样您可以确保 属性 实际上存在于对象实例上,并且您将获得合理的类型化结果而不是 any