【问题标题】:Retrieve return type of function w/o calling the function在不调用函数的情况下检索函数的返回类型
【发布时间】:2018-10-20 03:57:04
【问题描述】:

假设我在 TypeScript 中有这样的函数:

export const foo = function(){

   return {
     a: 1,
     b: true,
     c: 'bar'
   }

};

如果我将此函数导入另一个文件:

import {foo} from './foobar';

我的问题是 - 有没有办法获得 foo 的返回类型 而不 实际调用 foo

【问题讨论】:

  • 是的,这正是我想要的,但看起来有点老套
  • 如果你添加一个答案,我会赞成,但可能会等着看是否有更好的东西,然后再选择它作为接受的答案
  • 不就是ReturnType<typeof foo>吗?
  • 在需要时对 OP 的爱在哪里

标签: typescript typescript-typings typescript2.0 tsc


【解决方案1】:

Typescript 2.8 现在可以实现这一点

let foo = function() {
   return {
     a: 1,
     b: true,
     c: 'bar'
   }
};

type ComplexObj = ReturnType<typeof foo>;  // {a: number, b: boolean, c: string}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多