【问题标题】:Export return type of function in Typescript在 Typescript 中导出函数的返回类型
【发布时间】:2021-12-02 13:07:22
【问题描述】:

我有一个构建对象的函数,如下所示:

function toast() {
  return {
    a: "a",
    b: "b"
  }
}

我可以将函数的类型定义为

type ToastFunctionType = typeof toast

这种类型是

() => { a: string; b: string; }

但是,我只想要返回值的类型。是否可以提取 toast 的返回值的类型?在我的用例中,对象的实际值使用非常冗长的泛型类型参数。类型推断使它们恰到好处,我想避免维护一个非常冗长的接口(我需要导出)。

在吐司的情况下我想要的只是

{ a: string; b: string; }

【问题讨论】:

    标签: typescript


    【解决方案1】:

    是的,这是可能的。诀窍是在某处使用您需要的类型声明一些值(返回类型为toast()),而无需实际调用toast()。您可以通过引入另一个返回适当类型的值(实际值为 null)的函数来做到这一点,然后创建一个变量并将该函数返回的值分配给它,然后获取其中的 typeof

    我找不到不添加未使用变量的方法,但由于该变量由函数立即返回的null 初始化,我认为运行时开销可以忽略不计。代码如下:

    function toast() {
      return {
        a: "a",
        b: "b"
      }
    }
    
    function getReturnType<R> (f: (...args: any[]) => R): {returnType: R} {
        return null!;
    }
    
    // dummy variable, used for retrieving toast return type only
    let toastType = getReturnType(toast);
    
    export type ToastReturnType = typeof toastType.returnType;
    

    2018 年 2 月更新

    在即将发布的 2.8 版本中,some new language features 可以在不涉及虚拟变量和函数的情况下实现。

    这个例子用 typescript@next 编译:

    export function z() {
        return {a: 1, b: '2'}
    }
    
    export function v() {
    }
    
    type ReturnType<T extends (...args: any[]) => any> = 
        T extends (...args: any[]) => infer R ? R : never;
    
    export type RZ = ReturnType<typeof z>; // { a: number; b: string; }
    export type RV = ReturnType<typeof v>; // void
    

    TypeScript >= 2.8

    从 2.8 版开始,TypeScript 有一个您可以使用的 built-in generic ReturnType

    【讨论】:

    • 绝招!我自己不会想出这个。它看起来有点骇人听闻,但它通过删除 2 行的长声明使我们的应用程序受益。遗憾的是,不能在 typeof 之后使用表达式(类似于 typeof(ExtractReturnType(toast)),这比在 typeof 之后的变量声明更具可读性。
    • 如果strictNullChecks 开启,这将不起作用。 return null 会有错误。
    • @Louis 已修复,谢谢。这是您必须将非空断言运算符与 null 一起使用的罕见情况之一。
    • 请注意当前用户,通用ReturnType 现在已内置到语言中!很方便。
    猜你喜欢
    • 2021-12-25
    • 1970-01-01
    • 1970-01-01
    • 2021-05-09
    • 2019-05-04
    • 1970-01-01
    • 2021-01-03
    • 2019-09-03
    • 2021-10-06
    相关资源
    最近更新 更多