CHAPTER 8 · 3 lessons · 39 exercises

Type async code and APIs

`Promise<T>` for return types, `interface` for API shapes, `unknown` for data you cannot predict.

0 / 39 solved

You learnt async / await in the JavaScript course. In TypeScript the return type is Promise<T>. The awaited value's type goes inside the angle brackets — nothing else changes.

This chapter goes one step further: define the shape of data from a server. Write interface TodoItem { id: number; title: string; done: boolean } and a misspelled property is caught on the spot.

And finally, how to safely handle data whose type is unknown. Receive it as unknown, check with typeof, then use it. Unlike any, unknown will not let you through until you check.

Once you can do this, you have the typed foundation for "fetch, receive, render" in the next phase.

Lessons in this chapter

Type a Promise

  1. 34Type Promise and asyncAn async function returns Promise<T>. Write the awaited type inside the angle brackets.Go to the exercises

Define a response type

  1. 35Define a response typeWrite the shape of data from a server in an interface. Typos get caught on the spot.Go to the exercises

Receive safely with unknown

  1. 36Receive with unknown, narrow to useData you cannot predict gets unknown. Check it with a type guard before you touch it.Go to the exercises

Next up is “Design state with types”. Loading / Empty / Error / Success — express the four states of a screen as a discriminated union and catch every missing case.