【问题标题】:How do I get the return type of a class method in TypeScript如何在 TypeScript 中获取类方法的返回类型
【发布时间】:2019-04-16 18:31:36
【问题描述】:

在较新的 TypeScript 版本中(我认为是 2.8 以后的版本?),我可以轻松获得函数的返回类型:

function f() { return "hi"; }
type MyType = ReturnType<typeof f>; //MyType is string

但我无法从类方法中获取相同的信息……

class MyClass {
  foo() { return "hi"; }
}

如何获取(new MyClass()).foo()的返回类型?

【问题讨论】:

    标签: typescript typescript3.0


    【解决方案1】:

    要获取属性或方法类型,可以使用indexed access type operator

    type FooReturnType = ReturnType<MyClass['foo']>;
    

    【讨论】:

    • 我已经找了好几个小时了!谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多