Categories
TypeScript Answers

How to return a proper Promise with TypeScript?

Spread the love

Sometimes, we want to return a proper Promise with TypeScript.

In this article, we’ll look at how to return a proper Promise with TypeScript.

How to return a proper Promise with TypeScript?

To return a proper Promise with TypeScript, we can at the type for the resolved value of the promise.

For instance, we write

class C {
  //...
  saveMyClass(updatedMyClass: MyClass) {
    return new Promise<Package>((resolve, reject) => {
      const savedPackage: Package = updatedPackage;
      //...
      setTimeout(() => {
        resolve(savedPackage);
      }, 1500);
    });
  }
  //...
}

to return a promise in the saveMyClass method that has a Package object as the promise’s resolve value.

This is specified with <Package>.

We set savedPackage to the Package type and call resolve with it to make the code work with the type checks.

Conclusion

To return a proper Promise with TypeScript, we can at the type for the resolved value of the promise.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.