Skip to content

Suggestion: typechecking of 'this' context #15

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.

Activity

  1. metaweta commented on Dec 13, 2014

    @metaweta

    A solution to this problem would need to distinguish between methods that should only be used on instances of MyClass and methods that can be used on any object satisfying an interface that MyClass satisfies. For example, all the methods on Array.prototype are "generic" in the sense that they can be applied to any "array-like" object, i.e. one with a length property and numeric properties, not just to instances of Array.

  2. mhegazy commented on Feb 20, 2016

    @mhegazy
    Contributor

    This is now covered by #3694. PR is in #6739

  3. locked and limited conversation to collaborators on Jun 18, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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