Answer the question
In order to leave comments, you need to log in
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);
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question