Avoid any Types with Generics
Let's look at another practical example that you've probably written hundreds of times:
const fetchData = async (url: string) => { const data = await fetch(url).then((response) => response.json()); return data;};
This fetchData
function takes a url
string, fetches the da
Transcript
0:00 Let's look at another practical example. We have a fetchData function where we have a url.
0:05 string and we fetch that data, and we return it as JSON. You may have written this code hundreds of times. I know that I have.
0:11 Here what we're trying to do is say fetchData<{ name.string }>
0:15 and passing in the URL here. We're expecting data.name toEqual("Luke Skywalker"). Except the data is being returned as any. Your job is to try and figure out how to make fetchData generic enough that it can accept a type argument and also to assign that type argument to whatever gets returned.