Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript doesn't select the correct overload based on callback return type

Tags:

typescript

Given the following code (playground link: http://bit.ly/1n7Fcow)

declare function pick<T, V>(f:(x:T, y:V) => V):V;
declare function pick<T, V>(f:(x:T, y:V) => T):T;
var xx = pick((x: number, y:string) => x);
var yy = pick((x: number, y:string) => y);

TypeScript selects an incorrect overload and fails to infer the type of xx.

Is it possible to make typescript select the right overload there?

note: to avoid the XY problem, this is the original problem - http://bit.ly/QXaQGc - I need this kind of overloading in order to be able to model promises correctly.

like image 486
Gjorgi Kjosev Avatar asked May 18 '14 20:05

Gjorgi Kjosev


1 Answers

I was able to get the playground to infer the correct type of xx and yy correctly by changing the call to this:

declare function pick<T, V>( f:(x:T, y:V) => V ):V;
declare function pick<T, V>( f:(x:T, y:V) => T ):T;

var xx = pick<number,string>((x, y) => x);
var yx = pick<number,string>((x, y) => y);

See here: http://bit.ly/1p6h8iP Hope this help.

like image 187
micurs Avatar answered Sep 17 '22 19:09

micurs