2017-07-30 112 views
7

与函数的参数推断我有map功能:隐式类型的打字稿

const map = <T, U>(f: (x: T) => U, arr: T[]): U[] => { 
    return arr.map((val) => f(val)); 
} 

当我打电话map用匿名函数作为回调,它的返回类型是正确的:

// `x1` variable type here is { name: string }[], which is correct 
const x1 = map(x => x, [{name: 'John'}]); 

但当我提供identity函数而不是匿名函数时,返回类型是错误的:

const identity = <T>(x: T) => x 
// return type of `x2` is {}[] here 
const x2 = map(identity, [{name: 'John'}]); 

如何为第二个示例获取正确的类型结果,而不提供map函数的显式类型参数?

+1

如果你在'identity'上指定返回类型为'T',该怎么办? – jonrsharpe

+0

@jonrsharpe得到相同的结果。 – 1ven

+2

如果您切换map()参数的顺序,它可以正常工作。我想它迫使编译器首先匹配数组元素类型?我不知道是否有办法让推理按照您的顺序进行。 – jcalz

回答

2

经过一番尝试,我真的怀疑TypeScript能够跟得上你。 例如:

const x4 = map(identity, [2]); 
// x4 is '{}[]' 

这是obviosly甚至比你的例子更是错误的。

其他一些测试:

const x2 = map(<({ name: string }) => { name: string }>identity, [{ name: 'John' }]); 
// x2 is '{ name: string }[]' 

和:

const double = (x: number) => 2 * x; 
const x3 = map(double, [2]); 
// x3 is 'number[]' 

这让我得出这样的结论打字稿就不能打破所有泛型到一个有意义的类型,只是说:{}