简体   繁体   中英

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM