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

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

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

    He swears at this [method]: The element is implicitly of type "any", since an expression of type "string" cannot be used for indexing like "DomListener (my class)".
    An index signature with a parameter of type "string" was not found in type "DomListener" .:

    How can this problem be solved?
    JavaScript Anonymous, Feb 22, 2019

  • 1 Answers
  • 0
    In typescript, you cannot modify an existing class. A class is a complete entity. End.

    With inheritance, you can add new methods to a new inheriting 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.

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!