Promises and async/await

An async function returns a Promise of its resolved return type. If the function returns a User, its type is typically Promise<User>. await unwraps the promise result inside an async function, while thrown errors reject the returned promise.

Type the resolved value rather than annotating every intermediate expression unnecessarily. Use Promise<void> when asynchronous work has no meaningful result. Remember that TypeScript checks the declared types but cannot guarantee that a remote server actually returns the promised data shape.

Typed asynchronous function
type User = { id: string; name: string };

async function loadUser(id: string): Promise<User> {
  const response = await fetch(`/api/users/${id}`);
  if (!response.ok) throw new Error("Could not load user");
  return response.json() as Promise<User>;
}
💡 The return annotation says callers receive a promise for User. The assertion on response.json() is not runtime validation; in production, validate the decoded JSON before trusting it.
Key Takeaways
  • An async function always returns a Promise.
  • Promise<T> describes the resolved value type.
  • Network responses require runtime validation despite static annotations.
Knowledge Check

What is the return type of an async function declared `async function f(): Promise<number>`?