I’m using typescript 4.5.5
Maybe my understanding of TS isn’t that great.
I’m using arrow functions to create listeners for my elements. I would assume the context of this
to be always set to the same context as the caller and not the callee.
class MyClass {
someProperty: boolean = true;
// Ommited
constructor() {
this.myButton = document.createElement("input");
// this.myButton is of type HTMLInputElement
if (this.myButton) this.myButton.addEventListener("click", (e) => {
***this***.someProperty
// TS2684: The 'this' context of type 'this' is not assignable to method's 'this' of type 'HTMLInputElement'
});
this.myDiv = document.getElementById("myDiv");
// this.myDiv is of type HTMLElement
if (this.myDiv) this.myDiv.addEventListener("click", (e) => {
this.someProperty
// this is correctly set to MyClass
});
}
}
I’m pretty sure that’s the way I’ve been doing it for a couple of years now
this.myDiv
listener signaturelistener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any
this.myButton
listener signaturelistener: (this: HTMLInputElement, ev: MouseEvent) => any
Is there a valid reason why TS tries to assign this as MyClass
to this as HTMLInputElement
inside the listener?
Type 'MyClass' is missing the following properties from type 'HTMLInputElement': accept, align, alt, autocomplete, and 331 more.