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.
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.
related to https://github.com/Microsoft/TypeScript/issues/5616, and possibly https://github.com/Microsoft/TypeScript/issues/417, https://github.com/Microsoft/TypeScript/issues/5487, https://github.com/Microsoft/TypeScript/issues/9107, https://github.com/Microsoft/TypeScript/issues/9659, https://github.com/Microsoft/TypeScript/issues/9660,
https://github.com/Microsoft/TypeScript/issues/10247, https://github.com/Microsoft/TypeScript/issues/11311, https://github.com/Microsoft/TypeScript/issues/11343, https://github.com/Microsoft/TypeScript/issues/5616
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.