泛型函数的Typescript ReturnType

泛型函数的Typescript ReturnType

问题描述:

ReturnType"rel =" noreferrer > TypeScript 2.8 是一项非常有用的功能,可让您提取特定函数的返回类型.

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?

TypeScript编译器未将typeof foo视为通用类型.我会说这是编译器中的错误.

TypeScript compiler does not see typeof foo as generic type. I'd say it's a bug in the compiler.

但是,TypeScript具有可调用接口,该接口可以是通用的没有任何问题,因此,如果您引入一个与函数签名兼容的可调用接口,则可以像这样实现自己的ReturnType等效项:

However, TypeScript has callable interfaces which can be generic without any problems, so if you introduce a callable interface compatible with the signature of your function, you can implement your own equivalent of ReturnType like this:

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


interface Callable<R> {
  (...args: any[]): R;
}

type GenericReturnType<R, X> = X extends Callable<R> ? R : never;

type N = GenericReturnType<number, typeof foo>; // number