1

Closed

Problem with type inference on generic types with functions that return the type with different generic type

description

Sorry for the issue name, but I couldn't think of a better way to describe it.

See the following (incomplete) generic interface for a promise:
interface Promise<T> {
    then<U>(onFulfill?: (value: T) => U, onReject?: (reason: any) => U): Promise<U>;
}
I'm currently running into a problem with the following code:
declare var x: Promise<number>;

var z = x.then(num => num.toFixed()).then(str => str.length);

z.then(num => num.toExponential());
Tooling is telling me that z should be a Promise<string>, and the compiler fails on .toExponential, pointing out that num should be a string, even though length is of type number.

Labeling the second then as a number doesn't fix it either:
declare var x: Promise<number>;

var z = x.then(num => num.toFixed()).then<number>(str => str.length);

z.then(num => num.toExponential());
However, the following compiles, but tooling fails, again thinking the second num is a string:
declare var x: Promise<number>;

var z = x.then(num => num.toFixed())
    .then(str => str.length)
    .then(num => num.toExponential());
Though this fixes it:
var z: Promise<string> = x.then(num => num.toFixed())
    .then(str => str.length)
    .then(num => num.toExponential());
As does this:
var z: Promise<number> = x.then(num => num.toFixed())
    .then(str => str.length);

z.then(num => num.toExponential());
This also works, and y is correctly interpreted as Promise<string>:
declare var x: Promise<number>;

var z: Promise<string> = x.then(num => num.toFixed());

var y = z.then(str => str.length).then(num => num.toExponential());
Also, this compiles correctly for some reason, but it shouldn't:
declare var x: Promise<number>;

var z: Promise<string> = x.then(num => num.toFixed());

var y = z.then(str => str.length);

var g: Promise<string> = y.then<string>(num => num.toExponential());

g = g.then<number>(y => y.length);
Point is, weird stuff is going on with generics and I hope these examples help you pinpoint the problem.
Closed Aug 7, 2013 at 6:57 PM by RyanCavanaugh
This bug has been fixed. If you're still seeing this issue, please re-open the bug (click "Re-open Issue" below the "ISSUES" tab). Thanks!

comments

danquirk wrote Jun 21, 2013 at 3:21 AM

Thanks for the report, definitely some weirdness there we'll want to take a look at.

danquirk wrote Jun 28, 2013 at 6:58 PM

We'll have a hotfix out soon that fixes a bunch of the bugs here.

AndrewGaspar wrote Jun 28, 2013 at 10:46 PM

Thanks!

billti wrote Jun 29, 2013 at 12:31 AM

FYI: See FYI: See http://blogs.msdn.com/b/typescript/archive/2013/06/28/announcing-typescript-0-9-0-1.aspx . This release should address the core issue reported above (some of the other bugs will be fixed in a subsequent release).