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.
>Solution :
You’re missing some generics to complete the chain.
type CollectionGetter<T> = () => Collection<T>
By omitting <T> here, you were infering only any.