I seem to be facing some resistance filing a feature request related to this
on GitHub issues, so I'll give it a shot here.
Here is the code snippet that caused me trouble:
export class Example {
readonly myOtherElement: HTMLElement;
public constructor() {
this.myOtherElement = <HTMLFormElement>document.getElementById('myFormElement');
document.querySelector("form").addEventListener('submit', this.sendMessage);
}
private sendMessage(e: Event) {
this.myOtherElement.style.display = 'none';
}
}
This code needs to be adjusted for ES2015 output as follows:
Example = class Example {
constructor() {
this.myOtherElement = document.getElementById('myFormElement');
document.querySelector("form").addEventListener('submit', this.sendMessage);
}
sendMessage(e) {
this.myOtherElement.style.display = 'none';
}
};
The problem lies in this code. The context of this
changes within the event handler and causes this.myOtherElement
to become undefined.
To fix this issue, a lambda can be used:
document.querySelector("form").addEventListener('submit', e => this.sendMessage(e));
However, TypeScript IntelliSense inaccurately assumes that this.myOtherElement
will point to an HTMLElement
, leading to potential runtime errors. Adjusting TypeScript accordingly results in compilation errors:
private sendMessage(e: Event) {
this.style.display = 'none';
}
TypeScript still thinks this
is an instance of Example
, resulting in the following error:
Error TS2339 (TS) Property 'style' does not exist on type 'Example'.
In my opinion, one of the following solutions should be implemented:
When using
, the compiler should warn if there are references toaddEventListener('submit', this.sendMessage)
this
insendMessage
.The emitted code should differ based on context.
It's unclear whether the TypeScript team acknowledges this issue or if it's a challenging problem to solve?