Typescript 无法从函数参数推断泛型类型参数



考虑以下代码:

type Collection<T = any> = T[]
type CollectionGetter = () => Collection
function collectionProcessor(getter: CollectionGetter) {
const res = getter();
// some processing...
// return collection of the same type
return res;
}
// ---
interface Item {
id: number;
}
const myGetter = () => {
return [
{
id: 1
},
{
id: 2
},
{
id: 3
}
] as Collection<Item>
}
const result = collectionProcessor(myGetter);
// typeof result = Collection<any>
// expected: Collection<Item>
console.log(result);

TS操场

Typescript不能从传递给collectionProcessor的实参中推断出Collection<T>的类型形参。

这个例子的正确输入方式是什么?

我知道我可以像这样输入处理器function collectionProcessor<R>(getter: CollectionGetter): Collection<R>并显式传递类型collectionProcessor<Item>(myGetter),但这将不是很方便,因为参数是从更高的抽象级别传递下来的。

您缺少一些泛型来完成这个链。

type CollectionGetter<T> = () => Collection<T>

在这里省略<T>,您只推断any

游乐场

最新更新