Reading values from class dynamically leading to typescript error

69 Views Asked by At

I'm new and learning Typescript plus parallel implementing in my project. 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. 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]
1

There are 1 best solutions below

0
On BEST ANSWER

your class Base has a predefined set of properties (property1 and 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. 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