Change the return type of every function within the class while maintaining its generic nature

Looking for a solution to alter the return type of all functions within a class, while also maintaining generics.

Consider a MyService class:

class CustomPromise<T> extends Promise<T> {
  customData: string;
}

interface RespSomething {
  data: string;
}

interface RespWhatever {
  data: number;
}

class MyService {
  something(req: { x: string; y: string }): CustomPromise<RespSomething> {
    return new CustomPromise<RespSomething>((res, req) => {});
  }

  whatever(req: { a: string }): CustomPromise<RespWhatever> {
    return new CustomPromise<RespWhatever>((res, req) => {});
  }
}

The goal is to convert the type to:

interface TransformedMyService {
  something(req: { x: string; y: string }): Promise<RespSomething>;
  whatever(req: { a: string }): Promise<RespWhatever>;
}

I am pondering whether this can be achieved in TypeScript.

Answer №1

To achieve this, you can utilize the power of a mapped type with the help of conditional type inference to isolate the method argument types and define the appropriate type for CustomPromise<T>:

type ModifiedMyService = { [K in keyof MyService]:
  MyService[K] extends { (...args: infer A): CustomPromise<infer R> } ?
  { (...args: A): Promise<R> } :
  MyService[K]
}

This customized approach yields:

/*
type ModifiedMyService = {
    something: (req: {
        x: string;
        y: string;
    }) => Promise<RespSomething>;
    whatever: (req: {
        a: string;
    }) => Promise<RespWhatever>;
}
*/

Serving the expected outcome.

Access the Playpen for code

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

When using the async pipe with Angular's ngFor, an error message indicates that the argument is

Can you explain why this error message is appearing: Argument of type '[string, { startTime: string; endTime: string; }][] | null' is not assignable to parameter of type 'Collection<unknown>'. It occurs when attempting to utilize ...

Is it possible to switch the hamburger menu button to an X icon upon clicking in Vue 3 with the help of PrimeVue?

When the Menubar component is used, the hamburger menu automatically appears when resizing the browser window. However, I want to change the icon from pi-bars to pi-times when that button is clicked. Is there a way to achieve this? I am uncertain of how t ...

Tips for adjusting the radio button value similarly to a checkbox in Angular 2 using *ngFor

my checkbox and radio button implementation: <input id="{{k.group_name}}_{{i}}" name="{{k.group_name}}" type="checkbox" class="hide" name="{{k.group_name}}" [value]="m.details" (change)="change($event, m , k.item_ingredient_group_key,false,k.maximum)"& ...

Change a nested for-loop into an Observable that has been transformed using RxJS

Currently, the following function is operational, but I consider it a temporary solution as I'm extracting .value from a BehaviorSubject instead of maintaining it as an observable. Existing Code Snippet get ActiveBikeFilters(): any { const upd ...

Using type aliases in Typescript to improve string interpolation

After working with Typescript for some time, I have delved into type aliases that come in the form: type Animal = "cat" | "dog"; let a1_end = "at"; let a1: Animal = `c${a1_end}` I initially thought that only the values "cat" ...

Experimenting with Nuxtjs application using AVA and TypeScript

I'm in the process of developing a Nuxt application using TypeScript and intend to conduct unit testing with AVA. Nonetheless, upon attempting to run a test, I encounter the following error message: ✖ No test files were found The @nuxt/typescrip ...

Encountering a Problem with TypeScript Decorators

I've been diving into TypeScript by working on TS-based Lit Elements and refactoring a small project of mine. However, I'm starting to feel frustrated because I can't seem to figure out what's wrong with this code. Even though it' ...

Tips for efficiently passing TypeScript constants to Vue templates without triggering excessive reactivity

I'm curious about the most efficient way to pass a constant value to a template. Currently, I am using the data property in Vue, but I believe that is better suited for state that changes over time as Vue adds event listeners to data properties. The c ...

I am attempting to make the fade in and out effect function properly in my slideshow

I've encountered an issue where the fading effect only occurs when the page initially loads and solely on the first image. Subsequently, the fading effect does not work on any other images displayed. This is the CSS code I have implemented by adding ...

Expanding a given type using Typescript

My goal is to construct a custom table using Angular, where I aim to define a TableItem type that enforces the presence of a label property for every item added to the table. For instance, consider this example: <app-my-table [items]="items&qu ...

Accessing environment-based constants in TypeScript beyond the scope of Cypress.env()Is there a way to gain access to environment-specific constants

Imagine I have an API test and the URL and Credentials are different between production and development environments: before("Authenticate with auth token", async () => { await spec().post(`${baseUrl}/auth`) .withBody( { ...

Setting a default value dynamically in a `select` control can be done by using JavaScript to

Upon subscribing to the HTTP server for data retrieval, my select control in Angular framework gets loaded with the received data. My objective is to set a default value that comprises three values from the server object separated by slashes ("/"), which r ...

When creating a new instance of the Date object in Javascript, the constructor will output a date that is

In my project using TypeScript (Angular 5), I encountered the following scenario: let date = new Date(2018, 8, 17, 14, 0); The expected output should be "Fri Aug 17 2018 14:00:00 GMT-0400 (Eastern Daylight Time)", but instead, it is returning: Mon Sep ...

Compiling errors arise due to TypeScript 2.4 Generic Inference

Experiencing issues with existing TypeScript code breaking due to changes in generic inference. For instance: interface Task { num: number; } interface MyTask extends Task { description: string; } interface Job {} type Executor<J> = <T ...

How can I center align my loader inside app-root in Angular2+?

I've successfully added a basic spinner to my <app-root> in the index.html file. This gives the appearance that something is happening behind the scenes while waiting for my app to fully load, rather than showing a blank white page. However, I& ...

transferring data between components in a software system

I received a response from the server and now I want to pass this response to another component for display. I attempted one method but ended up with undefined results. You can check out how I tried here: how to pass one component service response to other ...

When the button is clicked, a fresh row will be added to the table and filled with data

In my table, I display the Article Number and Description of werbedata. After populating all the data in the table, I want to add a new article and description. When I click on 'add', that row should remain unchanged with blank fields added below ...

Retrieve all exports from a module within a single file using Typescript/Javascript ES6 through programmatic means

I aim to extract the types of all module exports by iterating through them. I believe that this information should be accessible during compile time export const a = 123; export const b = 321; // Is there a way to achieve something similar in TypeScript/ ...

How can I dynamically change and load a configuration file based on the URL parameter using Angular?

My query involves modifying the config file on pageload based on a URL parameter. I currently have implemented the following: config-loader.service.ts @Injectable() export class ConfigLoaderService { constructor(private injector: Injector, private ht ...

Customize styles for a specific React component in a Typescript project using MaterialUI and JSS

I'm currently exploring how to customize the CSS, formatting, and theme for a specific React component in a Typescript/React/MaterialUI/JSS project. The code snippet below is an example of what I've tried so far, but it seems like the {classes.gr ...