← All languages
TypeScript construct of the day
Random

async/await

Write asynchronous code with Promise-based types and sequential syntax.

Description

TypeScript fully supports async/await syntax with comprehensive type checking. An async function always returns a Promise, and TypeScript automatically wraps the return type in Promise<T>. The await keyword unwraps a Promise to its resolved value type.

TypeScript correctly infers the return type of async functions and validates that await is only used inside async functions or at the top level of modules. It also handles nested Promises, automatically flattening Promise<Promise<T>> to Promise<T>.

When typing async function signatures, you can annotate the return type as Promise<T> where T is the type of the resolved value. TypeScript also provides the Awaited<T> utility type for extracting the unwrapped type of a Promise at the type level.

Example

async function fetchUser(id: string): Promise<User> {
  const response = await fetch(`/api/users/${id}`);
  const data: User = await response.json();
  return data;
}

async function getUsers(): Promise<User[]> {
  const [alice, bob] = await Promise.all([
    fetchUser('1'),
    fetchUser('2')
  ]);
  return [alice, bob];
}

Reference