R
R
Rustam2020-06-08 22:52:10
typescript
Rustam, 2020-06-08 22:52:10

Typescript. How to type this?

Hello.
I have:

  • 1 parent class
  • 3 component classes, each of which will extend the parent

During initialization, components pass to the parent class an array of the names of their methods, which must be hung as a handler on the document.
The parent class runs through the array and hangs them on the document)
5ede95b48cab2627710736.png

How can I correctly specify the this type in this case?
In the parent class I do something like this:
this.listeners.forEach((listener) => {
    const method: string = getMethodName(listener);

    if (method in this) {
      this[method] = this[method].bind(this);
      this.$root.addEventListener(listener, this[method]);
    }
});

Error at this[method]
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Listener'.   No index signature with a parameter of type 'string' was found on type 'Listener'.


I know TS doesn't understand what exactly this string is, but I don't know how to solve it.
any is not used, tsconfig is set to strict: true

I don't mind if you suggest a different approach

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
juxifo, 2020-06-09
@juxifo

What, sorry? Doesn't bother you, does it? You already have a scope - .
this[method] = this[method].bind(this);

this.$root.addEventListener(listener, () => this[method]());

Check the type this[method]if it doesn't work.
Your implementation itself is a huge crutch, but you need to look at the whole code. Offhand, it would be better to make a public method (pseudocode):
public void on(string event, ((Event event) => void) callback)

And pull it, inheritance looks terrible here.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question