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 it
type GenericReturnType<F, T> = F extends (x: T) => (infer U) ? U : never
function 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 here
declare function thinger<T>(thing: T): ThingerReturn<T>;
// and here
interface 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!