Categories
TypeScript Answers

How to use promise generic types with TypeScript?

Spread the love

Sometimes, we want to use promise generic types with TypeScript.

In this article, we’ll look at how to use promise generic types with TypeScript.

How to use promise generic types with TypeScript?

To use promise generic types with TypeScript, we can use the Promise generic type.

For instance, we write

const test = (arg: string): Promise<number> => {
  return new Promise<number>((resolve, reject) => {
    if (arg === "a") {
      resolve(1);
    } else {
      reject("1");
    }
  });
};

to create the test function which returns a promise.

To add the return type for the return value, we set the return type to Promise<number>.

This means the promise return would resolve to a number.

Therefore, call resolve with a number in the Promise constructor callback would match the required return type.

Conclusion

To use promise generic types with TypeScript, we can use the Promise generic type.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *