从类动态读取值导致打字稿错误

问题描述

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...