我有 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
函数提供显式类型参数的情况下获得第二个示例的正确类型结果?
最佳答案
经过一些尝试,老实说,我怀疑 TypeScript 能否跟上你的步伐。 例如:
const x4 = map(identity, [2]);
// x4 is '{}[]'
这显然比你的例子更错误。
一些其他测试:
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[]'
这让我得出结论,TypeScript 无法将所有泛型分解为有意义的类型,而只是说{}。
关于typescript - 在 Typescript 中使用函数参数进行隐式类型推断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45402457/