Lesson 10 of 10
Promise types
- 15 min
- 5 checks
- 3 hints
- Go to task
Goal
Every await gets its own type
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.
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- No type errors
- The summary is correct
- Both calls run at the same time
- User is the type inside the promise
- User rejects an incomplete object