简体   繁体   中英

TypeScript: Is it possible to get the return type of a generic function?

I have exported a function from some module that looks like:

export function MyFunc<A>() {
    return {
        foo: (in: A) => void
    }
}

Now, in some other module, I want to be able to talk about the different return types of MyFunc . Since I didn't export the type, I'll use typeof to get hold of the type I want given the value MyFunc . Ideally I would do the following :

import { MyFunc } from "mymodule";
type MyFuncReturned<A> = ReturnType<typeof MyFunc<A>>;

function foo(): MyFuncReturned<string> {
   // ...
}

Hrmph, this doesn't work; typeof can only be passed a value and doesn't like my attempt to specify the generic type of that value.

The best I can do is convincing TypeScript to infer specific types of MyFunc from values I've created, and then giving them individual type aliases, eg:

const myFuncStringReturn = MyFunc<string>();
type MyFuncStringReturn = typeof myFuncStringReturn;

To avoid actually running MyFunc just to get the type info, I can hide it behind a function and use ReturnType on it:

const myFuncStringReturn = () => MyFunc<string>();
type MyFuncStringReturn = ReturnType<typeof myFuncStringReturn>;

const myFuncBoolReturn = () => MyFunc<bool>();
type MyFuncBoolReturn = ReturnType<typeof myFuncBoolReturn>;

This gives me a way of, one type at a time, talking about the different return types of MyFunc , but it

  • Involves actual runtime code to be written that TS can infer from.
  • Doesn't let me talk about MyFunc in a more generic sense.

The only "proper" solution I can come up with is duplicating a bunch of type info when I declare MyFunc :

export function MyFunc<A>(): MyFuncReturns<A> {
    return {
        foo: (in: A) => void
    }
}

export type MyFuncReturns<A> = {
    foo: (in: A) => void
}

But now as I change MyFunc , I have to make sure to keep MyFuncReturns in sync with it.

Is there any way I can get hold of a type like MyFuncReturns<A> given just our exported value MyFunc , without having to add runtime code or add the boilerplate above?

There is a proposal to allow using typeof with arbitrary expressions to allow things like getting the return type of a generic functions for a specific type argument (see here and here )

A more generic workaround that works today is to use a generic class with a field that is tied to the return type of the function. We can then extract the field of the class. Since for classes we can specify generic type parameters in type expressions we can extract the generic form of the return type:

export function MyFunc<A>() {
  return {
    foo: (os : A) => {}
  }
}

class Helper <T> {
  Return = MyFunc<T>()
}
type FuncReturnType<T> = Helper<T>['Return']
type ForBool = FuncReturnType<boolean> //  {foo: (os: boolean) => void;}
type ForString = FuncReturnType<string> //  {foo: (os: string) => void;}

Note If you have constraints of A you will need to duplicate those on T in Helper and FuncReturnType , that is unavoidable unfortunately.

It's a long time but TypeScript finally supported it. Since v4.7 (still in beta as of this writing), with the help of Instantiation Expressions feature we can now do this:

 function myFunc<A>() { return { foo: (a: A) => { } } } type MyFuncReturnType<A> = ReturnType<typeof myFunc<A>>; const a: MyFuncReturnType<string> = { foo: (a) => { console.log(a.toUpperCase()); } }; const b: MyFuncReturnType<number> = { foo: (a) => { console.log(a.toFixed(2)); } };

I created this playground so people can play with it. See here and here for more information.

Titian's solution above works great if the Generic is only applied inside the function body.

However, there are cases that the Generic Type is a part of the arguments and/or return type. eg

function MyFunc3<T extends object | number | string>(r: number, p: T, x: boolean): T {
    return p;
}

So, to generalize Titian's solution and support fixating both the arguments and the return type of any generic function, I wrote the following:

Required Utility Types

// From https://stackoverflow.com/a/53808212 by jcalz (https://stackoverflow.com/users/2887218)
export type IfEquals<T, U, Y=unknown, N=never> =
    (<G>() => G extends T ? 1 : 2) extends
    (<G>() => G extends U ? 1 : 2) ? Y : N;

// Aidin: Please comment if you could make the following shorter!
type ReplaceType<T, FROM_TYPE, TO_TYPE> = IfEquals<T, FROM_TYPE, TO_TYPE, T>;
type ReplaceTypeInArray<ARR, F, T> =
    ARR extends [] ? []
    : ARR extends [infer P0] ? [P0 extends F ? T : P0]
    : ARR extends [infer P0, infer P1] ? [ReplaceType<P0, F, T>, ReplaceType<P1, F, T>]
    : ARR extends [infer P0, infer P1, infer P2] ? [ReplaceType<P0, F, T>, ReplaceType<P1, F, T>, ReplaceType<P2, F, T>]
    : ARR extends [infer P0, infer P1, infer P2, infer P3] ? [ReplaceType<P0, F, T>, ReplaceType<P1, F, T>, ReplaceType<P2, F, T>, ReplaceType<P3, F, T>]
    : ARR extends [infer P0, infer P1, infer P2, infer P3, infer P4] ? [ReplaceType<P0, F, T>, ReplaceType<P1, F, T>, ReplaceType<P2, F, T>, ReplaceType<P3, F, T>, ReplaceType<P4, F, T>]
    : ARR extends [infer P0, infer P1, infer P2, infer P3, infer P4, infer P5] ? [ReplaceType<P0, F, T>, ReplaceType<P1, F, T>, ReplaceType<P2, F, T>, ReplaceType<P3, F, T>, ReplaceType<P4, F, T>, ReplaceType<P5, F, T>]
    : ARR extends [infer P0, infer P1, infer P2, infer P3, infer P4, infer P5, infer P6] ? [ReplaceType<P0, F, T>, ReplaceType<P1, F, T>, ReplaceType<P2, F, T>, ReplaceType<P3, F, T>, ReplaceType<P4, F, T>, ReplaceType<P5, F, T>, ReplaceType<P6, F, T>]
    : ARR extends [infer P0, infer P1, infer P2, infer P3, infer P4, infer P5, infer P6, infer P7] ? [ReplaceType<P0, F, T>, ReplaceType<P1, F, T>, ReplaceType<P2, F, T>, ReplaceType<P3, F, T>, ReplaceType<P4, F, T>, ReplaceType<P5, F, T>, ReplaceType<P6, F, T>, ReplaceType<P7, F, T>]
    : ARR extends [infer P0, infer P1, infer P2, infer P3, infer P4, infer P5, infer P6, infer P7, infer P8] ? [ReplaceType<P0, F, T>, ReplaceType<P1, F, T>, ReplaceType<P2, F, T>, ReplaceType<P3, F, T>, ReplaceType<P4, F, T>, ReplaceType<P5, F, T>, ReplaceType<P6, F, T>, ReplaceType<P7, F, T>, ReplaceType<P8, F, T>]
    : never;

Sample Functions

type ALL = string | number | object | boolean;

export function MyFunc1<T extends ALL>() {
  return {
    foo: (os : T) => {}
  }
}

function MyFunc2<T extends ALL>(r: 55, p: T, x: boolean): T {
    return p;
}

Fixation examples

// Inspired by https://stackoverflow.com/a/52964723 by Titian (https://stackoverflow.com/users/125734)
class Helper1 <T extends ALL> {
    Fixate = (...args: ReplaceTypeInArray<Parameters<typeof MyFunc1>, ALL, T>) => MyFunc1<T>(...args);
}
type FixatedFunc1<T extends ALL> = Helper1<T>['Fixate'];

// -- Usage

type ForNumber1 = FixatedFunc1<number> //  {foo: (os: number) => void;}
type ForString1 = FixatedFunc1<string> //  {foo: (os: string) => void;}

// ~~~~~~~~~~~~~~~~~~~

class Helper2 <T extends ALL> {
    Fixate = (...args: ReplaceTypeInArray<Parameters<typeof MyFunc2>, ALL, T>) => MyFunc2<T>(...args);
}
type FixatedFunc2<T extends ALL> = Helper2<T>['Fixate'];

// -- Usage

type ForNumber2 = FixatedFunc2<number> //  (args_0: 55, args_1: number, args_2: boolean) => number
type ForString2 = FixatedFunc2<string> //  (args_0: 55, args_1: string, args_2: boolean) => string

Playground Link (Contains all 3 parts)

Now, one can simply use ReturnType<T> or Parameteres<T> on any of these fixated function types!

Expanding on Aidin's answer, I've managed to make ReplaceTypeIn , which works for any number of elements, objects as well as arrays, and uses only a couple of lines:

// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Derived from https://stackoverflow.com/a/53808212 by jcalz (https://stackoverflow.com/users/2887218)
export type IfEquals<T, U, Y=unknown, N=never> =
    (<G>() => G extends T ? 1 : 2) extends
    (<G>() => G extends U ? 1 : 2) ? Y : N;

type ReplaceType<T, FROM_TYPE, TO_TYPE> = IfEquals<T, FROM_TYPE, TO_TYPE, T>;
type ReplaceTypeIn<T, FROM_TYPE, TO_TYPE> = {
  [K in keyof T]: ReplaceType<T[K], FROM_TYPE, TO_TYPE>;
};

// ~~~~~~~~~~~~~~~~~~~~~~ SAMPLE FUNCTIONS ~~~~~~~~~~~~~~~~~~~

export function MyFunc1<T extends unknown>() {
  return {
    foo: (os: T) => {}
  }
}

function MyFunc2<T extends unknown>(r: 55, p: T, x: boolean): T {
    return p;
}

// ~~~~~~~~~~~~~~~~~~~~~ FIXATIONS ~~~~~~~~~~~~~~~~~~~~

// Derived from https://stackoverflow.com/a/52964723 by Titian (https://stackoverflow.com/users/125734)
class Helper1 <T extends unknown> {
    Fixate = (...args: ReplaceTypeIn<Parameters<typeof MyFunc1>, unknown, T>) => MyFunc1<T>(...args);
}
type FixatedFunc1<T extends unknown> = Helper1<T>['Fixate'];

// -- Usage

type ForNumber1 = FixatedFunc1<number> //  {foo: (os: number) => void;}
type ForString1 = FixatedFunc1<string> //  {foo: (os: string) => void;}

// ~~~~~~~~~~~~~~~~~~~

class Helper2 <T extends unknown> {
    Fixate = (...args: ReplaceTypeIn<Parameters<typeof MyFunc2>, unknown, T>) => MyFunc2<T>(...args);
}
type FixatedFunc2<T extends unknown> = Helper2<T>['Fixate'];

// -- Usage

type ForNumber2 = FixatedFunc2<number> //  (r: 55, p: number, x: boolean) => number
type ForString2 = FixatedFunc2<string> //  (r: 55, p: string, x: boolean) => string

Here's a playground link for the example above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM