Skip to content

tsc does not infer "this" correctly in MyClass.prototype.getData syntax #13621

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

Closed
michael-brade opened this issue Jan 22, 2017 · 3 comments
Closed
Labels
Question An issue which isn't directly actionable in code

Comments

@michael-brade
Copy link

TypeScript Version: 2.1.4

Code

Consider this:

class MyClass {
  data: string;
  wrongData: {};
}

interface MyClass {
  getData(): string;
}

MyClass.prototype.getData = function() {
  return this.wrongData; // this.data;
};

Expected behavior:

VS Code should show an error, tsc should refuse to compile it. Hovering this in VS Code should show MyClass, not any.

Actual behavior:

TypeScript 2.1.4 compiles this without complaining. VS Code doesn't show an error. It infers correctly that getData() should return a string, but it thinks this is any.

@mhegazy
Copy link
Contributor

mhegazy commented Jan 23, 2017

If this type is not specified, it is inferred to be any. consider adding a this declaration to your interface:

interface MyClass {
  getData(this:MyClass): string;
}

@mhegazy mhegazy added the Question An issue which isn't directly actionable in code label Jan 23, 2017
@michael-brade
Copy link
Author

michael-brade commented Jan 25, 2017

Well, I guess this is a bit more verbose but it would work as a workaround for now. However, it looks ugly and seems totally unneccessary. MyClass.prototype.xxxx already implies that this is MyClass, doesn't it? So why can't or shouldn't TypeScript infer this correctly?

@mhegazy
Copy link
Contributor

mhegazy commented Jan 25, 2017

Please see #10288

@mhegazy mhegazy closed this as completed Feb 28, 2017
@microsoft microsoft locked and limited conversation to collaborators Jun 19, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Question An issue which isn't directly actionable in code
Projects
None yet
Development

No branches or pull requests

2 participants