How can we ensure a generic async function with a return type that is also generic in Typescript?

I'm currently working on a function that retries an async function multiple times before rejecting. I want to make sure the typescript typings of the retry function are maintained and also ensure that the passed function is of type PromiseLike.

Creating a retry function with a typed response inferred from the passed function is doable, but enforcing that the passed function is PromiseLike can be challenging. If we wrap the ReturnType<T> in a promise as shown below, we end up returning a promise of a promise of T, Promise<Promise<T>> instead of Promise<T>:

export async function retry<T extends () => ReturnType<T>>(fn: T, retries: number = 1) {
  let attempts = 0;
  let response: ReturnType<T>;
  
  while (attempts < retries) {
    response = fn();
    try {
      console.log(`Evaluating attempt #${attempts} ...`);
      return await response;
    } catch (e) {
      console.log(`Attempt #${attempts} failed.`);
      if (attempts < retries) attempts = attempts + 1;
      else return response;
    }
  }
}

The main challenge I'm facing is how to enforce that the generic constraint is an asynchronous function rather than just any Callable. Using TS utilities like Promise and PromiseLike won't work since the return type will end up being wrapped twice with a promise when dealing with an asynchronous function.

Answer №1

To effectively address this issue, one can utilize the

PromiseLike<Awaited<T>>
method, which ensures that the provided function operates asynchronously. This specific combination is comparable to a constraint known as PromiseLike, particularly when anticipating that T will be a promise.

export async function retry<T extends () => PromiseLike<Awaited<ReturnType<T>>>>(fn: T, retries: number = 1) {
  let attempts = 0;
  let response: PromiseLike<Awaited<ReturnType<T>>>;
  
  while (attempts < retries) {
    response = fn();
    try {
      console.log(`Evaluating attempt #${attempts} ...`);
      return await response;
    } catch (e) {
      console.log(`Attempt #${attempts} failed.`);
      if (attempts < retries) attempts = attempts + 1;
      else return response;
    }
  }

  throw Error("Invalid number of retries");
}

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

Typescript's identification of a dispute between RequireJS and NodeJS definitions

I obtained the Typescript RequireJS definition from Definitely Typed. It includes an ambient declaration of Require that clashes with the NodeJs command "require". See below for the declaration and the error message: Declaration: declare var require: Req ...

"String representation" compared to the method toString()

Currently, I am in the process of writing unit tests using jasmine. During this process, I encountered an issue with the following code snippet: let arg0: string = http.put.calls.argsFor(0) as string; if(arg0.search(...) This resulted in an error stating ...

Next.js routes handlers do not have defined methods parameters

Struggling to find the cause of undefined params Currently delving into the world of Nextjs api routes, I keep encountering an issue where my params are coming up as undefined when trying to use them in the HTTP method. My setup includes prisma as my ORM ...

ngModelChange doesn't trigger if the value is manually altered

Here is the scenario I am experiencing: //html <input (ngModelChange)="onSelection()" [(ngModel)]="selectedNode" > // in the ts file onSelection() { alert('changed'); } Typing something inside the input tri ...

Inspecting an unspecified generic parameter for absence yields T & ({} | null)

Recently, I came across a perplexing issue while responding to this specific inquiry. It pertains to a scenario where a generic function's parameter is optional and its type involves the use of generics. Consider the following function structure: func ...

Searching Local JSON Data in Ionic 4 with a Filter Input Bar

My current challenge involves filtering local JSON data in my Ionic project. Despite referencing other resources, I am unable to filter or display filtered items on the ngx-datatable. I suspect the issue may lie either in the filterItems function implement ...

Tips for minimizing disagreements while implementing optional generic kind in TypeScript?

An issue arises in StateFunction due to its optional second generic type that defaults to a value. Even when omitting this second generic, undefined still needs to be passed as an argument, which contradicts the idea of it being optional. While making arg ...

How to detect changes in Angular 2 using a separate service

Within my AuthService, I store real-time user data and a method for logging in. When the 'Login' button is clicked, the AuthService is called to retrieve updated user data from the server and update the value of 'this.user'. As a resul ...

What is the proper method for specifying the path to my index.tsx file within a React application?

After using npx create-react-app my-app --template typescript to generate my React app, I decided to reorganize the files by moving them to /src/client and relocating my Express backend to /src/server. However, upon running the relocated React app, I encou ...

Check if a value is present in the array with *ngIf

I'm curious about how to use the ngIf directive in a specific scenario. In my Angular application, I have dynamically generated angular material toggles, each with a unique id. I'm familiar with using ngIf to conditionally display elements on the ...

The value of this.$refs.<refField> in Vue.js with TypeScript is not defined

During the process of converting my VueJs project to TypeScript, I encountered an error related to TypeScript. This issue arises from a component with a custom v-model implementation. In the HTML, there is an input field with a 'plate' ref that ...

Chrome fails the karma tests while phantomjs passes them

I've been struggling with this issue for some time now and can't seem to find a solution. I'm working on an Ionic 2 project that utilizes Angular 2's testing environment. When I run 'ng test' using Karma's Chrome launcher ...

Updating the FormControl value using the ControlValueAccessor

I have developed a directive specifically for case manipulation. The code I created successfully updates the visual value using _Renderer2, but I am facing an issue with formGroup.value. Even though the directive visually changes the value as expected, t ...

Issue with TypeScript Decorator Not Properly Overriding Get/Set Functions for Instance Properties

I'm struggling with creating a TypeScript decorator that modifies the get method for a property within a class. The issue I'm facing is getting it to affect instances of the class. Below is an example scenario: function CustomDecorator() { r ...

how to sort arrays in javascript

When it comes to filtering items based on specific criteria like fruit and vegetable filters, what is the most effective method to retrieve items that meet both filter requirements? fruitfilter: [] = [{fruitname: "apple"} , {fruitname: "orange"}] vegeta ...

Discriminator-based deserializer with strong typing

Seeking advice on how to effectively utilize TypeScript for strongly typing a function that operates similarly to the following example: function createDeserializer(typeDeserializers) { return (data) => { const deserializer = typeDeserializ ...

Understanding Different Symbols in TypeScript

Can you explain the purpose of symbols in TypeScript to me? As someone familiar with Java, it seems a bit unnecessary to use them alongside an interface declaration. What is the reason for setting symbols in TypeScript? For example, consider the followin ...

Having trouble locating modules or properties with ANTLR4 TypeScript target?

Having reached a frustrating impasse, I am seeking assistance with a perplexing issue. My attempt to integrate TypeScript with ANTLR4 has hit a snag, and despite exhaustive efforts, I am unable to pinpoint the root cause (with limited documentation availab ...

Unable to destructure props and assign them to a react-bootstrap component

I recently installed react-bootstrap and I am looking to customize the default buttons in my project. My goal is to simplify the button creation process by just using <Button> without specifying a variant option for most buttons. import * as bs from ...

Switching from module.exports in Javascript to Typescript format

My Node-express code currently uses module.exports to export functions. As I am converting the code to TypeScript, I need to find out how to replace module.exports in typescript. Can you help me with this? ...