【问题标题】:How do I extract all methods' ReturnType<T> of class (while ReturnType<T> and usage seem static)如何提取类的所有方法的 ReturnType<T> (而 ReturnType<T> 和用法似乎是静态的)
【发布时间】:2020-06-27 00:18:22
【问题描述】:

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

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

接近想法的例子

例如:

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 很奇怪。

请帮忙!

【问题讨论】:

  • 您想如何处理订单? [{message: string}, {shouldDo: boolean}][{shouldDo: boolean}, {message: string}] 不一样
  • @HTN,正确!它们不一样,也不应该出现在示例中。我猜你是因为示例中的拼写错误而问的。我会修复它。谢谢你的发现。至于顺序,其实无所谓。我更感兴趣的是了解如何针对查询类进行开发并提取 ReturnType 其方法。

标签: typescript generics decorator typescript-generics


【解决方案1】:

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

请参阅此处了解更多信息: Returning a Type as a Variable in TypeScript

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-30
    • 2020-01-28
    • 2022-01-19
    • 1970-01-01
    • 1970-01-01
    • 2021-11-18
    • 2012-07-20
    • 2022-11-03
    相关资源
    最近更新 更多