Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
755 views
in Technique[技术] by (71.8m points)

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

Disclaimer: overly simplified functions follow, I'm aware they're useless

function thinger<T>(thing: T): T {
    return thing;
}

const thing = thinger({ a: "lol" });

thing.a;

The above code transpiles just fine. But I need to place result of thinger<T> into an object.

interface ThingHolder {
    thing: ReturnType<typeof thinger>;
}

const myThingHolder: ThingHolder = {
    thing: thinger({ a: "lol" }),
};

However I have lost my type information so myThingHolder.thing.a does not work

Property 'a' does not exist on type '{}'

So I tried the following

interface ThingHolder<T> {
    thing: ReturnType<typeof thinger<T>>;
}

const myThingHolder: ThingHolder<{ a: string }> = {
    thing: thinger({ a: "lol" }),
};

But typeof thinger<T> is not valid typescript.

How can I get the return type of a function which has a different return type based on generics?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...