Specifying Promise Return Types in TypeScript
Let's look at how you can explicitly define the return type of a Promise
.
This is done through a type annotation, clarifying the expected value type the promise will resolve with.
Without this specification, the promise's resolve type is implicitly set to any
, which lacks the safety and predictiveness TypeScript is valued for.
For instance, to declare a promise that resolves with a number, you would write:
const numberPromise: Promise<number> = new Promise((resolve, reject) => { // The promise is designed to resolve with a numerical value });
In this example, numberPromise
is created to fulfill with a number
type.
Introducing a resolve with a type contrary to the declared one (e.g., a string
) will prompt TypeScript to flag an error, reinforcing type safety.
Note
This doesn't handle rejection types. In the case of rejections, it's standard practice to reject with an instance of Error
.