【发布时间】:2020-04-05 01:01:27
【问题描述】:
问题在标题中。下面是我想要实现的示例:
const apiResponse = Promise.resolve({data: 1} as {data: any}); // Assume I don't know the type of data
const mapData = <T>(res: {data: T}): T => res.data;
const x = apiResponse.then(mapData<number>); // This one fails to compile
const y = apiResponse.then(mapData); // Succeeded but y is of type any
const z = apiResponse.then(_ => mapData<number>(_)); // Succeeded but verbose !
【问题讨论】:
-
调用时只能指定泛型函数类型的类型参数。
_ => f<T>(_)可能是您在这里合理希望的最佳选择。
标签: typescript typescript-generics