TypeScript ยท Chapter 41 of 44

TypeScript with Async/Await and Promises

TypeScript can type Promises using the generic `Promise<T>` type, where T is the type of the value the promise eventually resolves to. This makes asynchronous code just as type-safe as synchronous code.

When you use `async` functions, TypeScript automatically wraps the declared return type in a Promise, and `await` unwraps a Promise back to its underlying value type inside an async function.

Syntax
async function getUser(): Promise<User> {
  return { name: "Ana", age: 30 };
}

Typing Promises

A function that fetches a number asynchronously can be typed as `function getNumber(): Promise<number>`, telling callers exactly what type they'll receive once it resolves.

async/await with types

Inside an `async function`, using `await somePromise` gives you the resolved value with the correct type directly, without needing `.then()` callbacks.

Example 1 (typescript)
function delay(ms: number): Promise<void> {
  return new Promise(resolve => setTimeout(resolve, ms));
}
async function run() {
  console.log("Start");
  await delay(100);
  console.log("End");
}
run();
Output
Start
End

delay returns a Promise<void>, and await pauses execution until it resolves.

Example 2 (typescript)
interface User {
  name: string;
}
async function fetchUser(): Promise<User> {
  return { name: "Mia" };
}
async function show() {
  const user = await fetchUser();
  console.log(user.name);
}
show();
Output
Mia

await unwraps the Promise<User> to give a plain User value with full type safety.

Key points

  • Promise<T> describes a promise that resolves with a value of type T.
  • async functions automatically wrap their return type in a Promise.
  • await unwraps a Promise to its resolved value type inside async functions.
  • TypeScript keeps asynchronous code just as type-safe as synchronous code.
๐Ÿ’ก Note: Use Promise<void> for async functions that perform an action but don't return a meaningful value.

๐Ÿ“ Quick Quiz

1. What does Promise<number> describe?

2. What does an async function's return type automatically become?

3. What does `await` do inside an async function?