Skip to content

thisType of callback parameter isn't enforced if the callback has another parameter #10850

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
Arnavion opened this issue Sep 11, 2016 · 2 comments
Labels
Duplicate An existing issue was already created Fixed A PR has been merged for this issue

Comments

@Arnavion
Copy link
Contributor

TypeScript Version: 2.1.0-dev.20160910

Code

declare function foo(cb: (this: number, arg: string) => void): void;

foo(function (): void { this.length; }); // (1)
foo(function (arg: string): void { this.length; }); // (2)

tsc -t es5 ./foo.ts

Expected behavior:

Both (1) and (2) should complain about length not existing on number

Actual behavior:
(1) correctly complains: foo.ts(3,30): error TS2339: Property 'length' does not exist on type 'number'. But there is no error for (2).

Adding --noImplicitAny doesn't change the result.

Adding --noImplicitThis gives foo.ts(4,36): error TS2683: 'this' implicitly has type 'any' because it does not have a type annotation. which confirms that this in (2) is getting inferred as any

@RyanCavanaugh
Copy link
Member

Same root cause as #4241 - due to the arg: string type annotation, the entire function is not contextually typed. #4241 removes the restriction that type annotations in functions "turn off" contextual typing. Should be an easy change if you want to take a stab at it.

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Sep 12, 2016
@Arnavion
Copy link
Contributor Author

Ah, you're right. The : string annotation is unnecessary and removing it allows this to be inferred correctly. I didn't think to try that.

@ahejlsberg ahejlsberg added the Fixed A PR has been merged for this issue label Oct 18, 2016
@mhegazy mhegazy added this to the TypeScript 2.1 milestone Oct 18, 2016
@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
Duplicate An existing issue was already created Fixed A PR has been merged for this issue
Projects
None yet
Development

No branches or pull requests

4 participants