Is there a way to retrieve the ReturnType<T> for all methods within a class, even if the ReturnType<T> and its usage appear to be static?

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!

Answer №1

It appears to be a challenging task as you aim to utilize types as values during runtime, which is unattainable due to the fact that types are restricted to compile-time operations in TypeScript.

For further insights, you can refer to: Exploring the Concept of Returning a Type as a Variable in TypeScript

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I retrieve all element attributes in TypeScript using Protractor?

I came across this solution for fetching all attributes using protractor: Get all element attributes using protractor However, I am working with TypeScript and Angular 6 and struggling to implement the above method. This is what I have tried so far: im ...

The Typescript generics are unable to be assigned to type T

Take a look at my code snippet: interface IDoc { doSomething(): void } class IDocFoo implements IDoc { doSomething(): void { console.log('Do doSomething'); } } class IDocFactory { getIDocInstance<T extends IDoc>(): T { re ...

Click function for mat-step event handler

Is it feasible to create a click event for the mat-step button? I want to be able to add a (click) event for each mat-step button that triggers a method. Essentially, I am looking to make the mat-step button function like a regular button. You can find mo ...

The successful operation of 'Ionic serve --lab' may involve the need to manually save the app.module

We are currently working on an Ionic project that consists of several pages and a single custom provider named request.ts. The issue we are facing is that whenever we launch it using the command ionic serve --lab, the compilation fails (with the error poin ...

Using capital letters with interpolated language keys

The issue: I'm currently facing a problem with i18next. It allows variable interpolation in strings, like "AddNew": "Add new {{item}}". However, I have a language where the grammar requires "{{item}}" to be the first word, as in "AddNew": "{{item}} t ...

Removing a targeted element from an array in Angular

After receiving a JSON array object in Angular using TypeScript, I am attempting to remove a specified object from it. However, my attempts at deletion have been unsuccessful. addCategorySub(categorySub: CategorySubModel, index: number) { categorySub.id ...

Creating detailed documentation comments for TypeScript within Visual Studio

When using C# with ReSharper and StyleCop, I am able to automatically generate basic documentation comments for methods. This includes sections such as: /// <summary> /// The login. /// </summary> /// <param name="returnUrl" ...

The number in Typescript should fall between 0 and 1, inclusive

Is there a method in Typescript that guarantees the value of a number will be less than or greater than a certain threshold? Currently, it permits the specification of a range of values, but I'm unsure about comparison. This is similar to what I have ...

angular 6's distinctUntilChanged() function is not producing the desired results

I have a function that retrieves an observable like so: constructor(private _http: HttpClient) {} getUsers(location){ return this._http.get(`https://someurl?location=${location}`) .pipe( map((response: any) => response), ...

Module not located following the completion of project compilation

Below is the content of my package.json file: { "main": "./build/app.js", "types": "./build/app.d.ts", "scripts": { "start": "tsc && node build/app.js", "dev": "concurrently \"tsc -w \" \"nodemon ...

The variable is currently undefined because it has an array assigned to it

Upon selecting multiple checkboxes for variants, I am retrieving checked data using the following method: get selectedIdsFromViolCategoriesFormArray(): string[] { return this.violCategories .filter((cat, catIdx) => this.violCategoriesFormArr. ...

Converting a TypeScript object into a JSON string

When working with TypeScript, I am facing a challenge while trying to initialize an object that requires a JSON string for the "options" parameter. Specifically, it pertains to the object mentioned here. It is crucial that the options parameter be in JSON ...

Issue with ngFor displaying only the second item in the array

There are supposed to be two editable input fields for each section, with corresponding data. However, only the second JSON from the sample is being displayed in both sections. The JSON in the TypeScript file appears as follows: this.sample = [ { "se ...

Dealing with Uncaught Promises in Angular 2 while injecting a service

I followed the instructions in the official tutorial to start a project, but I'm encountering an issue with injecting services into my Angular2 app. Everything was working fine until I added a service. Here are the files : app.component.ts import ...

Having difficulties viewing the sidemenu icon on Ionic 3, despite enabling the menu through MenuController

I am trying to show the sidemenu icon on my Home page, which users can access from the Add-Contract page. Even though I have enabled the sidemenu in home.ts using this.menu.enable(true);, the icon is not visible. However, I can still swipe and access the ...

The mat-slide-toggle component does not recognize the checked binding

My angular app contains the mat-slide-toggle functionality. switchValue: {{ switch }} <br /> <mat-slide-toggle [checked]="switch" (toggleChange)="toggle()">Toggle me!</mat-slide-toggle> </div> This is how the ...

Having difficulty forming queries correctly using TypeScript, React, and GraphQL

Apologies for the potentially naive question, but I am new to working with GraphQL and React. I am attempting to create a component that contains a GraphQL query and incoming props. The props consist of a query that should be passed into the GraphQL query. ...

Ways to dynamically apply styles to the component tag depending on the visibility of its content

Consider a scenario where you have a component with logic to toggle the visibility of its contents: @Component({ selector: 'hello', template: `<div *ngIf="visible"> <h1>Hello {{name}}!</h1></div>`, styles: [`h1 { fo ...

What is the best way to sort a union based on the existence or non-existence of a specific

My API response comes in the form of a IResponse, which can have different variations based on a URL search parameter. Here is how I plan to utilize it: const data1 = await request<E<"aaa">>('/api/data/1?type=aaa'); const d ...

Creating TypeScript types for enums can make your code more robust and ensure that you are using

I need to create an interface based on the values of an enum for a React use-case. The enum contains key value pairs that are used as form IDs. When the value of an input element is changed in an event listener, I want to set the state using this.setState( ...