Typescript: Type inference for generic functions

Created on 11 Oct 2016  路  9Comments  路  Source: microsoft/TypeScript

TypeScript Version: 2.0.3

Code

function id<T>(v: T): T { return v; }

function applyToNumber<T>(v: T, toNumber: (x: T) => number): number {
    return toNumber(v);
}

applyToNumber(5, v => v); // ok
applyToNumber(5, id); // ok
applyToNumber("aaa", v => v); // error, as expected.
applyToNumber("aaa", id); // ok, but an error is expected.

Expected behavior:
error

Actual behavior:
no error.

Fixed

All 9 comments

Related: #11311

might be dup a new shiny case of #3038

If it's compatibility problem, it would be really helpful to have a "strictTyping" compilation mode which would prohibit converting the any type to other types without explicit cast.

they say without any it will be an infinite recursion which i don't get because an explicit lambda (v => v in your case) doesn't have this problem, if so.. why would not TS handle all function references as explicit lambdas behind the scenes to avoid this recursion problem

An ugly workaround

function getId<T>(): (v: T) => T { return v => v; }

applyToNumber(5, getId()); // error, can't infer the 'T' type.
applyToNumber(5, getId<number>()); // ok but 'v => v' looks better.

looks like its time to bite that bullet or else you gonna break that all time record of the number of open issues related to the same problemo

The sample given:

applyToNumber("aaa", id); // ok, but an error is expected.

in TS 2.6 returns error:

Argument of type '<T>(v: T) => T' is not assignable to parameter of type '(x: string) => number'.
  Type 'string' is not assignable to type 'number'.

So I assume it's fixed.

thanks! closing.

Was this page helpful?
0 / 5 - 0 ratings