Async code with types

Advanced

Introduction

Programs wait: for the network, a file, a timer, a user. JavaScript represents waiting with promises and writes waiting code with async and await. TypeScript types both ends: a promise of a user is Promise<User>, awaiting it gives a User, and an async function that forgets to return one is an error. This lesson covers typed async code, including the part types cannot see, errors.

How it works

An async function always returns a promise, so its return type is Promise<T>, where T is the type of the value it returns:

async function fetchUser(id: number): Promise<User> {
  await wait(100);
  return { id, name: "Ada" };
}

Inside an async function, await on a Promise<T> gives a T. Forgetting await is a classic bug, and the types catch it: const user = fetchUser(1) is a Promise<User>, and user.name is an error.

The combinators are typed precisely. Promise.all([fetchUser(1), fetchCount()]) gives a tuple [User, number], in the order of the list, and rejects as soon as any promise rejects. Promise.allSettled never rejects; it gives an array of results, each either { status: "fulfilled", value } or { status: "rejected", reason }, a discriminated union you narrow on status. Promise.race gives the first to settle.

Errors are where types stop. Anything can be thrown, not just Error objects, so in strict mode the variable in catch (error) has type unknown. Check it before use: error instanceof Error ? error.message : String(error). Also, a function's type does not say which errors it may throw.

For failures that callers are expected to handle, many TypeScript programs return a Result type instead of throwing:

type Result<T> = { ok: true; value: T } | { ok: false; error: string };

The caller must check ok before reading value, so the failure case cannot be forgotten. Exceptions remain right for real surprises, such as bugs and broken invariants.

Example

// Typed promises, async functions, Promise.all, and errors as unknown.
interface User {
  id: number;
  name: string;
}

function wait(ms: number): Promise<void> {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

async function fetchUser(id: number): Promise<User> {
  await wait(100 * id);
  if (id > 2) throw new Error("no user " + id);
  return { id, name: id === 1 ? "Ada" : "Alan" };
}

async function main(): Promise<void> {
  const ada = await fetchUser(1);
  console.log("got", ada.name);
  const both: User[] = await Promise.all([fetchUser(1), fetchUser(2)]);
  console.log(both.map((u) => u.name));
  try {
    await fetchUser(3);
  } catch (error: unknown) {
    const message = error instanceof Error ? error.message : String(error);
    console.log("failed:", message);
  }
}

main();
Open in compiler

Line by line

  1. wait returns a Promise<void> that settles after the given time.
  2. fetchUser is async and declares Promise<User>; it throws for ids above 2.
  3. await fetchUser(1) gives a User, so ada.name is allowed.
  4. Promise.all gives the users in the order they were asked for, after both are ready.
  5. The catch receives unknown; the code checks for an Error before reading message.

Expected result

got Ada
[ 'Ada', 'Alan' ]
failed: no user 3

In the real world

Every web request, database query and file read in a TypeScript server or app is a typed promise. Data-fetching libraries return results typed by what the server sends, often with a run-time check that the data really has that shape. Teams that work with many failing operations, such as payments or parsing, often adopt a Result type so that error handling is visible in every signature.

Common mistakes

  • Forgetting await, and then using a promise as if it were the value.
  • Reading error.message without a check, when the thrown value may not be an Error.
  • Running independent requests one after another with await in a loop, when Promise.all would run them together.
  • Assuming fetched JSON has the declared type: the type is a promise you made, not a check the computer made.

Best practices

  • Write the return type of every async function as Promise<T>.
  • Use Promise.all for independent work, and Promise.allSettled when some may fail.
  • Return a Result for expected failures; throw for bugs.

Summary

Async functions return Promise<T>, and await unwraps it to a T; Promise.all and Promise.allSettled keep the types and order of their inputs. Caught errors are unknown and must be checked. A Result union puts expected failures into the return type, so callers cannot forget to handle them.

Quick check

1. What is the return type of an async function that returns a number?
2. What is the type of error in catch (error) under strict mode?
3. What does Promise.all([a, b]) give if a is Promise<string> and b is Promise<number>?
4. Why return a Result union instead of throwing for expected failures?

Key takeaways

  • An async function returning T is typed Promise<T>, and await gives back the T.
  • Errors are unknown: check them, for example with instanceof Error, before reading a message.
  • A Result union makes callers handle failure, which a thrown error does not.

Practice problems for this lesson

My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.