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.