Lesson 10 of 10

Promise types

Goal

Every await gets its own type

01

Explanation

An async function always returns a promise, so the result of fetchUser(1) isn't a user but a Promise<...>. That's why a forgotten await can't slip by unnoticed: fetchUser(1).email is a compile error, because a promise has no email.

When a library doesn't export the return types of its functions, derive them yourself. ReturnType<typeof fetchUser> gives you the type of the promise, and Awaited pulls out the type inside it.

Promise.all keeps the type of each element by its position, so const [user, orders] = await Promise.all([fetchUser(id), fetchOrders(id)]) gives each variable its correct type. Both calls run at the same time, so you only wait as long as the slower one takes, not as long as both of them added together.

02

Your task

Define User as Awaited<ReturnType<typeof fetchUser>>, then write loadSummary(id: number): Promise<Summary> so it fetches the user and their orders together with Promise.all and returns { user, spent }, where spent is the sum of the total values.

Checks

5 checks
  1. No type errors
  2. The summary is correct
  3. Both calls run at the same time
  4. User is the type inside the promise
  5. User rejects an incomplete object
03

Hints

0/3
Track lessons0 of 10 done

Learn generics, discriminated unions and utility types, and see how the type system becomes a tool for designing your program.

Advanced level, 10 lessons, 2 hours in total.

main.ts
OutputTypeScript 5.9

Loading the TypeScript compiler. This only happens once. Your browser keeps it after that.

–/5

Checks start once the environment is ready.

5 checks listed under “Your task”.

Track lessons0 of 10 done

Learn generics, discriminated unions and utility types, and see how the type system becomes a tool for designing your program.

Advanced level, 10 lessons, 2 hours in total.