【发布时间】:2020-06-27 00:18:22
【问题描述】:
我浏览了 typescript 上的文档:https://www.typescriptlang.org/docs/handbook/utility-types.html#returntypet
我在这里搜索了两个ReturnType<T> 的情况,但它们似乎都是静态写出的,我知道必须有一种方法可以动态读出响应数据类型。
接近想法的例子:
- Rewrite error catching higher order function to catch async errors?
- Type that converts all the methods on an interface to return promises
- Is modifying method's return type by decorator possible?
例如:
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