Typescript: Incorrect inference for function expression with type annotation and generic

Created on 6 Jun 2017  Â·  3Comments  Â·  Source: microsoft/TypeScript

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?

Bug Fixed

Most helpful comment

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

All 3 comments

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"'

@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);
}

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

Was this page helpful?
0 / 5 - 0 ratings

Related issues

wmaurer picture wmaurer  Â·  3Comments

MartynasZilinskas picture MartynasZilinskas  Â·  3Comments

seanzer picture seanzer  Â·  3Comments

blendsdk picture blendsdk  Â·  3Comments

CyrusNajmabadi picture CyrusNajmabadi  Â·  3Comments