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

Incorrect inference for function expression with type annotation and generic #16293

Closed
OliverJAsh opened this issue Jun 6, 2017 · 3 comments
Closed
Assignees
Labels
Bug A bug in TypeScript Fixed A PR has been merged for this issue

Comments

@OliverJAsh
Copy link
Contributor

OliverJAsh commented Jun 6, 2017

#TypeScript Version: 2.3.4

Code

// I can conveniently annotate a function express with a type
// This is good because the types don't litter the implementation

{
    type add = (a: number) => (b: number) => number;
    const add: add = a => b => a + b; // a and b are type number
}

// However, if I try to do the same where the function type has a generic…

{
    type fn = <A>(a: A) => A;
    const fn: fn = a => a; // a is inferred as any, but expected A
}

Is there any way to annotate the function expression fn with the type fn without breaking inference for the parameters?

@T-Hugs
Copy link

T-Hugs commented Jun 6, 2017

a is inferred as any, but expected number

Why did you expect number? You don't have number anywhere in the second block.

const t = fn(42); // t has type '42'
const u = fn("hello"); // u has type '"hello"'

@OliverJAsh
Copy link
Contributor Author

@trevorsg Sorry, that was a mistake. I would expect to see the parameters typed as the generic, A, not as any.

Even when the generic is constrained, the parameters still show as any, which is especially misleading:

{
    type fn = <A extends string>(a: A) => A;
    const fn: fn = a => a; // a is inferred as any, but expected A

    const x = fn(1);
}

@ahejlsberg
Copy link
Member

@OliverJAsh Funny you should ask, I'm working on precisely that right now. Stay tuned for a PR.

@ahejlsberg ahejlsberg self-assigned this Jun 6, 2017
@ahejlsberg ahejlsberg added the Bug A bug in TypeScript label Jun 6, 2017
@mhegazy mhegazy added this to the TypeScript 2.4 milestone Jun 6, 2017
@ahejlsberg ahejlsberg added the Fixed A PR has been merged for this issue label Jun 6, 2017
@microsoft microsoft locked and limited conversation to collaborators Jun 14, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Bug A bug in TypeScript Fixed A PR has been merged for this issue
Projects
None yet
Development

No branches or pull requests

4 participants