Skip to content

Suggestion: typechecking of 'this' context #15

Closed
@RyanCavanaugh

Description

@RyanCavanaugh

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already createdNeeds ProposalThis issue needs a plan that clarifies the finer details of how it could be implemented.SuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions