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
函数的显式类型参数?
如果你在'identity'上指定返回类型为'T',该怎么办? – jonrsharpe
@jonrsharpe得到相同的结果。 – 1ven
如果您切换map()参数的顺序,它可以正常工作。我想它迫使编译器首先匹配数组元素类型?我不知道是否有办法让推理按照您的顺序进行。 – jcalz