← Back to TypeScript Course | Chapter 15: TypeScript with APIs | Lesson 6 of 6

Promise Types

A Promise represents a value that will become available asynchronously. TypeScript uses Promise<T> to describe the type of value produced when the asynchronous operation succeeds.

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

typescript
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

typescript
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

typescript
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

typescript
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

typescript
Promise.reject("custom string reason").catch((reason: unknown) => {
  console.log("Rejected with:", reason);
});
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.