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.
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
- 34Type Promise and asyncAn
asyncfunction returnsPromise<T>. Write the awaited type inside the angle brackets.Go to the exercises
Define a response type
- 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
- 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