首页 > 解决方案 > 如何提取所有方法的 ReturnType类(而 ReturnType和使用似乎是静态的)

问题描述

我浏览了 typescript 上的文档:https ://www.typescriptlang.org/docs/handbook/utility-types.html#returntypet

我在这里搜索并发现了两种情况ReturnType<T>,但它们似乎都是静态写出的,我知道必须有一种方法可以动态读出响应数据类型。

接近想法的例子:

例如:

class Idea1 {
    one() { return "one"; }
    two() { return "two"; }
}
class Idea2 {
    do() { return { message: "do-one" }; }
    process() { return { shouldDo: true }; }
}

// similar to the example I've seen
const i1 = new Idea1();
declare type R1 = ReturnType<typeof i1.one>; // string

const i2 = new Idea2();
type R2 = ReturnType<typeof i2.do>;  // { message: string }

我知道“典型”的方法是通过类型提取它,但是我如何提交一个类并获得一个返回类型列表?

喜欢(上面的类)

//what I'd love to see
getReturnTypes(Idea1) // [string, string]

//but I could always new it up first then pass it, and then passed in
getReturnTypes(new Idea2()) // [{message: string}, {shouldDo: boolean}]

主要是我希望能够获取方法返回信息

我在尝试了解如何以编程方式完成此流程时遇到了很糟糕的事情。我在页面上看到该类型的分配处于较高级别,因此为类的每个方法写出一个新类型作为另一种类型 ReturnType 很奇怪。

请帮忙!

标签: typescriptgenericsdecoratortypescript-generics

解决方案


在我看来,你想做的事情是不可能的,因为你想在运行时返回/使用类型作为值。但是,类型在 TS 中是仅编译时的。

有关更多信息,请参见此处: 在 TypeScript 中将类型作为变量返回


推荐阅读