Typing asynchronous code

Intermediate · 39 min

How TypeScript types promises and async functions: Promise<T>, Awaited<T>, Promise.all tuples, unknown in catch, and the floating promises tsc misses.

Before thisParameter and return typesWhy generics, and generic functionsany, unknown, never, and voidUtility types for unions and functions

Jack Herrington · 39 min

Typing asynchronous code

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Jack HerringtonReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A `Promise<T>` is a typed box for a value that arrives later; you only get the `T` out with `await` or `.then`, and TypeScript stops you from reading properties of the box as if they were the value.
  • An `async` function always returns a promise, so its return annotation is `Promise<T>`, and `return value` inside it must match `T`, not `Promise<T>`.
  • `Awaited<T>` names what `await` produces, unwrapping nested promises, and `Awaited<ReturnType<typeof fn>>` is the usual way to name what an async function resolves to.
  • `Promise.all` on an array literal resolves to a tuple, so destructuring its result gives each value its own type rather than a union.
  • Under `strict`, `useUnknownInCatchVariables` makes the `catch (err)` variable `unknown`, but the `reason` in a `.catch()` callback is still `any`, so narrow both before use.
  • `tsc` catches a promise used as a value, such as `if (isAdmin(id))`, but not a promise you call and never await; that floating promise needs typescript-eslint's `no-floating-promises` rule.

A value that isn’t there yet

A synchronous function hands you its result. An asynchronous one hands you a receipt, and the result shows up later. Think of a coffee shop buzzer: you can’t drink the buzzer, but it tells you which order you’ll get when it goes off. A promise is that buzzer, and how promises run is covered in the JavaScript roadmap’s lessons on promises and async/await. This lesson is about what the checker knows about them.

TypeScript writes the buzzer as Promise<T>, a generic type where T is the value it will deliver. The checker keeps the box and the contents apart:

type User = { id: string; name: string };

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

async function greet(id: string) {
  const pending = getUser(id);
  pending.name;
  // error TS2339: Property 'name' does not exist on type 'Promise<User>'.

  const user = await getUser(id); // user: User
  return `Hello, ${user.name}`;
}

That error is the most common async mistake there is, and the message points straight at it: the type is Promise<User>, so an await is missing.

Annotating async functions

An async function always returns a promise, whatever its body says. So the annotation is Promise<T>, while each return inside produces a plain T:

async function countUsers(): Promise<number> {
  return "3";
  // error: Type 'string' is not assignable to type 'number'.
}

Leave the annotation off and TypeScript infers Promise<...> from the returns, just as it does for ordinary return types. An annotation pays off on exported functions, where it pins the contract.

Notice that getUser above compiles even though res.json() returns Promise<any>. The Promise<User> annotation is a claim, not a check: any is assignable to User, so nothing verified the server’s response. Validating untrusted data at runtime is how you earn that type honestly.

When you build a promise by hand, give the constructor its type argument, because there is nothing to infer it from:

const wait = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));

Naming the resolved type with Awaited

Sometimes you need the type a promise resolves to without writing it out. Awaited<T> models the await keyword at the type level, unwrapping nested promises until it reaches a non-promise:

async function loadDashboard(id: string) {
  return { user: await getUser(id), loadedAt: new Date() };
}

type Dashboard = Awaited<ReturnType<typeof loadDashboard>>;
// { user: User; loadedAt: Date }

The standard library uses it in generic code too. Promise.resolve accepts either a value or a promise and returns Promise<Awaited<T>>, so passing it a Promise<number> gives back Promise<number>, never Promise<Promise<number>>.

Promise.all keeps each position’s type

Running independent requests at once is the point of Promise.all, and its type preserves which result is which:

type Settings = { theme: "light" | "dark" };
declare function getSettings(): Promise<Settings>;
declare function getCount(): Promise<number>;

async function header(id: string) {
  const [user, settings, count] = await Promise.all([
    getUser(id),
    getSettings(),
    getCount(),
  ]);
  // user: User, settings: Settings, count: number
  return `${user.name} (${settings.theme}) has ${count} items`;
}

The array literal is inferred as a tuple, and Promise.all maps each position through Awaited. Build the same array with push and its type is a plain array, Promise<User | Settings | number>[], so every element comes back as the union. Promise.allSettled works the same way, returning a result per position that you narrow on status === "fulfilled".

Errors arrive as unknown

JavaScript lets code throw anything: an Error, a string, undefined. Since TypeScript 4.4, the useUnknownInCatchVariables flag, part of strict, types the catch variable as unknown, so you narrow before touching it:

async function safeLoad(id: string): Promise<User | null> {
  try {
    return await getUser(id);
  } catch (err) {
    if (err instanceof Error) console.error(err.message);
    else console.error("Non-error thrown:", err);
    return null;
  }
}

The return await matters here. Without await, the promise is returned before it settles, and a rejection skips this catch entirely.

One gap remains. The callback to .catch() is typed (reason: any) in the standard library, and the flag doesn’t change that. Annotate it yourself, .catch((reason: unknown) => ...), to get the same safety.

Floating promises

The checker catches a promise used where a value was meant:

declare function isAdmin(id: string): Promise<boolean>;

function label(id: string) {
  if (isAdmin(id)) return "admin";
  // error TS2801: This condition will always return true since this
  //               'Promise<boolean>' is always defined.
  return "user";
}

It does not catch a promise you call and never await. save(user); in a click handler compiles, runs in the background, and an error inside it becomes an unhandled rejection that no try around the call will see. That’s a floating promise. typescript-eslint’s no-floating-promises rule, covered in linting with typescript-eslint, reports these, and void save(user) marks the ones you mean to ignore.

About the video

Jack Herrington’s 39-minute session builds async patterns up in TypeScript: typed promises with then and catch, async/await with try/catch, writing your own Promise<T>, using promises as a cache, Promise.all, pooling, and testing async code. It’s from 2021, so it predates Awaited and doesn’t show the unknown catch variable in action; the sections above cover both. ByteGrad’s video in the links focuses on unknown in catch, and basarat’s four-minute clip covers Awaited.

Check yourself

  1. 01Why does `async function count(): Promise<number> { return "3"; }` fail, when the function body never mentions a promise?

    An `async` function wraps whatever it returns in a promise, so the body's `return` must produce the inner type. The annotation says that inner type is `number`, and `"3"` is a `string`, so the return is rejected.

  2. 02`const user = getUser(id); user.name;` gives `Property 'name' does not exist on type 'Promise<User>'`. What went wrong?

    The call returned the promise, not the user, because the `await` is missing. The error message names the real type, `Promise<User>`, which is the clue. Writing `const user = await getUser(id);` fixes it.

  3. 03What type does `err` have in `try { ... } catch (err) { ... }` under `strict`, and why?

    It is `unknown`, because `useUnknownInCatchVariables` is part of the `strict` family. JavaScript lets code throw any value, not only `Error` objects, so TypeScript makes you narrow, for example with `err instanceof Error`, before reading `err.message`.

  4. 04Why is `const [user, count] = await Promise.all([getUser(id), getCount()])` better typed than awaiting an array built with `push`?

    With an array literal, TypeScript infers a tuple and `Promise.all` maps each position to its awaited type, so `user` is `User` and `count` is `number`. An array built with `push` has a plain array type like `Promise<User | number>[]`, so each element comes back as the union.

  5. 05Why doesn't `tsc` report `save(user);` inside a non-async click handler when `save` returns a promise?

    Calling a function and ignoring its result is legal, and `tsc` has no rule about unhandled promises. The promise floats: nobody awaits it, and a rejection goes unhandled. typescript-eslint's `no-floating-promises` reports it, and `void save(user)` marks the cases where ignoring it is deliberate.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark