typescriptgenerics

Typescript ReturnType of generic function


The new ReturnType in TypeScript 2.8 is a really useful feature that lets you extract the return type of a particular function.

function foo(e: number): number {
    return e;
}

type fooReturn = ReturnType<typeof foo>; // number

However, I'm having trouble using it in the context of generic functions.

function foo<T>(e: T): T {
    return e;
}

type fooReturn = ReturnType<typeof foo>; // type fooReturn = {}

type fooReturn = ReturnType<typeof foo<number>>; // syntax error

type fooReturn = ReturnType<(typeof foo)<number>>; // syntax error

Is there a way extract the return type that a generic function would have given particular type parameters?


Solution

  • You can extract the return type of a generic function instantiated with specific type parameters in TypeScript. However, you can not do this directly with "ReturnType<typeof foo>" this is invalid syntax. You can do this using an intermediate step. You can use a helper function signature to instantiate the generic function, and then extract the return type from that signature. As outlined below:

    function foo<T>(e: T): T {
      return e;
    }
    
    type FooWithNumber = (e: number) => number;
    
    type FooReturn = ReturnType<FooWithNumber>;