[英]Reading values from class dynamically leading to typescript error
I'm new and learning Typescript plus parallel implementing in my project.我是新手,正在学习 Typescript 以及在我的项目中并行实现。 I have class of written in typescript as follows:我用打字稿写的类如下:
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'
}
}
Now tsc
command is giving following error which is not much understandable to me.现在tsc
命令给出了以下错误,这对我来说不太好理解。 Please help.请帮忙。
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]
your class Base
has a predefined set of properties ( property1
and property2
).您的类Base
具有一组预定义的属性( property1
和property2
)。 Typescript is aware of this, so when you are trying to access a property of Base
by a random string name (that field: string
), it's telling you that you are probably doing something you shouldn't. Typescript 意识到这一点,因此当您尝试通过随机字符串名称(该field: string
)访问Base
的属性时,它告诉您可能正在做一些不应该做的事情。 Try changing it to field: keyof Base
- this way you are ensuring that the the property actually exists on the object instance and you are getting a sensible typed result and not any
尝试将其更改为field: keyof Base
- 这样您就可以确保该属性实际存在于对象实例上,并且您获得了合理的类型化结果,而不是any
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.