通用函数的 Typescript ReturnType [英] Typescript ReturnType of generic function

查看:24
本文介绍了通用函数的 Typescript ReturnType的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这篇关于通用函数的 Typescript ReturnType的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆