[英]Reading values from class dynamically leading to typescript error
我是新手,正在學習 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 意識到這一點,因此當您嘗試通過隨機字符串名稱(該field: string
)訪問Base
的屬性時,它告訴您可能正在做一些不應該做的事情。 嘗試將其更改為field: keyof Base
- 這樣您就可以確保該屬性實際存在於對象實例上,並且您獲得了合理的類型化結果,而不是any
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.