Essential Types And Notations 20 exercises
Problem

Typing Fetch API Responses in Async Functions

Here's our first look at an async function.

The fetchData function awaits the response from a call to fetch, then gets the data by calling response.json():


async function fetchData() {
const response = await fetch("https://api.example.com/data");
const data = await respo

Loading exercise

Transcript

00:00 In this exercise, we're going to look at an async function for the first time and start handling promises. We can see that inside FetchData, this function, we have a response, and that response is coming from a WaitFetch, and we're just fetching some example data.

00:16 And this response then, it's basically a response type, which is a globally available type, and we're calling response.json on it, which returns PromiseAny there. So we hover over that, we can see it's returning PromiseAny, and that means that data ends up as Any.

00:34 If we remove this Await there, it actually is PromiseAny, which is kind of interesting. So that's worth bearing in mind. Now, except this data that we're fetching, it's actually just going to give us a number. So your job is to try to work out how you can make data typed as a number without changing any of this code down here.

00:53 So this is the only code that you're going to be changing. So there are a few ways around this. One involves adding a type to FetchData itself. One involves typing data itself. And because we're dealing with Any, it's going to be fairly flexible in the types that you can add. Good luck.