0

我是新手,在我的项目中学习 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]
4

1 回答 1

1

你的类Base有一组预定义的属性(property1property2)。Typescript 意识到了这一点,因此当您尝试Base通过随机字符串名称(that field: string)访问属性时,它会告诉您您可能正在做一些您不应该做的事情。尝试将其更改为field: keyof Base- 这样您可以确保该属性实际存在于对象实例上,并且您将获得合理的类型化结果,而不是any

于 2021-06-19T20:40:34.840 回答