A
A
Alexey Golubev2020-11-14 14:26:55
JavaScript
Alexey Golubev, 2020-11-14 14:26:55

How to dynamically add a method to a class, inside the same class?

I want to dynamically create new methods in one of the class methods, the names of which are also created in the process of work.

initDOMListeners() {
    this.listeners.forEach(list => {
      const method = capitalize(list)
      this[method] =  this[method].bind(this)
      this.$root.on(list, this[method])
    })
  }


On this[method] swears: The element is implicitly of type "any", since an expression of type "string" cannot be used to index the type "DomListener(my class)".
Index signature with type parameter "string" was not found on type 'DomListener'.:

How can I solve this problem?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Aetae, 2020-11-14
@Aetae

In typescript, you cannot change an existing class. A class is a complete entity. End.
With inheritance, you can add new methods to a new derived class .
And of course, you can hack anything that is possible in javascript, forcibly bypassing ts, but ts will not know about it and, accordingly, no typing.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question