Promise Types
In this page:
const promise: Promise<Type> = new Promise((resolve, reject) => {
resolve(value);
});
Basic Promise Types
A basic Promise<T> type describes what value the promise will eventually resolve with, so a function returning Promise<string> promises a string once awaited, not a string right away.
Example: Basic Promise Types
function getGreeting(): Promise<string> {
return Promise.resolve("hello");
}
getGreeting().then((s) => console.log(s));
Promises with Object Types
A promise resolving with an object type — Promise<User> — lets you access the resolved object's properties with full autocomplete after awaiting it, exactly as if you'd received the object synchronously.
Example: Promises with Object Types
interface User { name: string; }
function getUser(): Promise<User> {
return Promise.resolve({ name: "Ravi" });
}
getUser().then((u) => console.log(u.name));
Promise Arrays
An array of promises, typed as Promise<T>[], is a common shape for kicking off several concurrent operations before awaiting them together, distinct from Promise<T[]> which is a single promise resolving to an array.
Example: Promise Arrays
const tasks: Promise<number>[] = [Promise.resolve(1), Promise.resolve(2)];
console.log(tasks.length);
Promise.all and Promise Types
Promise.all converts an array of promises into one promise resolving to an array of their results, and its type signature infers each result's type from the corresponding input promise automatically.
Example: Promise.all and Promise Types
const tasks: [Promise<number>, Promise<string>] = [Promise.resolve(1), Promise.resolve("a")];
Promise.all(tasks).then(([n, s]) => console.log(n, s));
Promise Rejection Types
A rejected promise's type is unknown in TypeScript, mirroring how caught exceptions are typed, since JavaScript allows rejecting a promise with literally any value, not necessarily an Error instance.
Example: Promise Rejection Types
Promise.reject("custom string reason").catch((reason: unknown) => {
console.log("Rejected with:", reason);
});
- Writing the return type as
stringinstead ofPromise<string>for a function that returns a promise. - Using
.thenresult without handling rejection, so errors go unhandled. - Passing an array of promises to
Promise.alland expecting a plain array back withoutawait.
- The Fetch API and Axios can be used with types so requests and responses are checked.
- Defining types for API responses documents the data your code expects.
- Typed error handling,
async/await, andPromisetypes keep asynchronous code predictable.
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: