After extensively reviewing the documentation on typescript at https://www.typescriptlang.org/docs/handbook/utility-types.html#returntypet, I have come across two instances of ReturnType<T>
mentioned. However, these instances appear to be statically written out, and I am convinced there must be a way to dynamically retrieve the response data type.
Here are some examples that are close to the concept I am trying to achieve:
- 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?
For instance:
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 }
While the standard approach involves extracting the information via type, I am seeking a way to input a class and receive a list of return types.
For instance (using the classes above):
//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}]
The main goal is to be able to access method return information programmatically.
I am struggling to comprehend how to navigate through this process efficiently. The assignment of the type seems to be at a high level on the page, making it cumbersome to create a new type for each method of the class as another ReturnType.
Assistance is greatly appreciated!