typescript - 在 Typescript 中使用函数参数进行隐式类型推断

标签 typescript

我有 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/

相关文章:

.net - 在列数据夹点 Angular 2 中显示列表

typescript - 如何使用不完整的类型

typescript :如何对将函数映射转换为具有不同类型参数的类似函数的函数进行强类型化?

javascript - 呈现 View 后使用 aurelia 将数据动态添加到页面

javascript - Angular/Typescript——通过示例解释接口(interface)的好处

angular - Ionic 3 值绑定(bind)地理定位

javascript - 在 typescript 中导出默认值后实例化对象返回错误

typescript - 如何在 nest.js 中创建装饰器?

javascript - 动态更改 typescript 装饰器

javascript - Angular 中嵌套订阅的错误