英文:
Typescript can't infer a generic type parameter from function arguments
问题
以下是代码的翻译部分:
type Collection<T = any> = T[]
type CollectionGetter = () => Collection
function collectionProcessor(getter: CollectionGetter) {
const res = getter();
// 进行一些处理...
// 返回相同类型的集合
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>
// 期望:Collection<Item>
console.log(result);
希望这个翻译对您有所帮助。
英文:
Consider the following code:
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);
Typescript can't infer the Collection<T>
type parameter from the argument passed to collectionProcessor
.
What is the right way to type this example?
I know I can type the processor like this function collectionProcessor<R>(getter: CollectionGetter): Collection<R>
and pass the type explicitly collectionProcessor<Item>(myGetter)
, but that would not be very convenient as the argument is passed down from higher levels of abstraction.
答案1
得分: 2
你漏掉了一些泛型以完成链式。
type CollectionGetter<T> = () => Collection<T>
在这里省略 <T>
,你只推断出 any
。
英文:
You're missing some generics to complete the chain.
type CollectionGetter<T> = () => Collection<T>
By omitting <T>
here, you were infering only any
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论