R
R
Rustem2020-05-12 22:14:02
typescript
Rustem, 2020-05-12 22:14:02

How to correctly cast the type of a method through this in a class in TypeScript?

at first the code was written in JS, now I am rewriting it in TS.
there is a base class:

import { Dom } from './dom';
import { capitalize } from './utils';
export class DomListener {
  private $root: Dom;
  private listeners: string[];

  constructor($root: Dom, listeners: string[] = []) {
    if (!$root) {
      throw new Error('No $root provided for DomListener');
    }
    this.$root = $root;
    this.listeners = listeners;
  }

  initDomListener() {
    console.log(this);
    this.listeners.forEach((listener) => {
      const method = getMethodName(listener);
      if (!this[method]) {
        throw new Error(`Method ${method} is not implemented in ${name} Component`);
      }
      this[method] = this[method].bind(this);
      this.$root.on(listener, this[method]);
    });
  }
}
function getMethodName(eventName: string) {
  return 'on' + capitalize(eventName);
}


from which the intermediate and further end element class is inherited.
in the intermediate class, init is called, which in turn calls initDomListener from the main one, the essence of the whole action is to rebind methods from the final element to the base class context.
and set event listeners.
the code itself works, but TS gives warnings on this[method]:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'DomListener'.
No index signature with a parameter of type 'string' was found on type 'DomListener'.

help get rid of them.
Thank you!!!

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question