Closed
Description
A common error in TypeScript is to lose the this
context, especially in class situations:
class MyClass {
x = 4;
printX() { console.log(this.x); }
}
var m = new MyClass();
window.setInterval(m.printX, 1000); // Prints 'undefined', not '4'
The compiler should detect when this happens and issue an error:
var m = new MyClass();
// Error, `this` context might be lost
window.setInterval(m.printX, 1000);
We need a proposal here that determines why this would be an error, in a way that is not burdensome. For example, we do want it to be valid to call e.g. function#bind
on m.printX
, and it should probably valid to write something like if(m.printX) { m.printX() }
.
This gets even trickier when we look at the members of window
-- some of them can be invoked with any this
, but others cannot. It should be possible to describe these differences.