Getting the return type of a function which uses generics Getting the return type of a function which uses generics typescript typescript

Getting the return type of a function which uses generics


I might as well put this in an answer although it doesn't look like it will meet your needs. TypeScript currently has neither generic values, higher kinded types, nor typeof on arbitrary expressions. Generics in TypeScript are sort of "shallow" that way. So as far as I know there's unfortunately no way to describe a type function that plugs type parameters into generic functions and checks the result:

// doesn't work, don't try ittype GenericReturnType<F, T> = F extends (x: T) => (infer U) ? U : neverfunction thinger<T>(thing: T): T {  return thing;}// just {}, 🙁type ReturnThinger<T> = GenericReturnType<typeof thinger, T>;

So all I can do for you is suggest workarounds. The most obvious workaround would be to use a type alias to describe what thinger() returns, and then use it multiple places. This is a "backwards" version of what you want; instead of extracting the return type from the function, you build the function from the return type:

type ThingerReturn<T> = T; // or whatever complicated type you have// use it heredeclare function thinger<T>(thing: T): ThingerReturn<T>;// and hereinterface ThingHolder<T> {  thing: ThingerReturn<T>;}// and then this works 🙂 const myThingHolder: ThingHolder<{ a: string }> = {  thing: thinger({ a: "lol" }),};

Does that help? I know it's not what you wanted, but hopefully it's at least a possible path forward for you. Good luck!


Probably this would solve the problem. But you need to create a fake class. It works because classes are types and JS-runtime objects at the same time.

// generic function// we want to get its result, but we cannot do it like// ReturnType<typeof foo<T>()> // syntax errorconst foo = <T,>(arg: T) => ({ test: arg });// so, let's create a parametric classclass Wrapper<T> {  // with the only method that uses our "foo"  wrapped = (arg: T) => foo(arg);   };// due to the fact that class is a type we can use it as a type // with a generic parameter.type GetFooResult<T> = ReturnType<Wrapper<T>['wrapped']>type Bingo = GetFooResult<number>; // { test: number }

TS Playground link. Based on this answer. Thx to @Colin