Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Typescript can't infer a generic type parameter from function arguments

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);

TS Playground

Typescript can’t infer the Collection<T> type parameter from the argument passed to collectionProcessor.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading