Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Suggestion: typechecking of 'this' context #15

Closed
RyanCavanaugh opened this issue Jul 15, 2014 · 2 comments
Closed

Suggestion: typechecking of 'this' context #15

RyanCavanaugh opened this issue Jul 15, 2014 · 2 comments
Labels
Duplicate An existing issue was already created Needs Proposal This issue needs a plan that clarifies the finer details of how it could be implemented. Suggestion An idea for TypeScript

Comments

@RyanCavanaugh
Copy link
Member

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.

@metaweta
Copy link

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.

@mhegazy
Copy link
Contributor

mhegazy commented Feb 20, 2016

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

@mhegazy mhegazy closed this as completed Feb 20, 2016
@mhegazy mhegazy added the Duplicate An existing issue was already created label Feb 20, 2016
@microsoft microsoft locked and limited conversation to collaborators Jun 18, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Duplicate An existing issue was already created Needs Proposal This issue needs a plan that clarifies the finer details of how it could be implemented. Suggestion An idea for TypeScript
Projects
None yet
Development

No branches or pull requests

3 participants