Home > Software design >  How to correctly define TypeScript types for API response
How to correctly define TypeScript types for API response

Time:07-25

I am trying to get data from REST Countries API: https://restcountries.com/. The problem is that return data contains a lot of data and more than I need. The question is can i define TypeScript types only that i need? For example:

interface ICountry {
    name: string;
    capital: string;
    flag: string;
    population: number;
} 

But i don't really understand what to do with the rest of the data. Maybe it is possible during the fetching extract only the ones i need?

CodePudding user response:

After fetching the data you can just store the values you need in your data variable and disregard the rest.

So if you are doing:

const res = fetchCountries();
const data = res.data.map(country => {name: country.name, capital: country.capital etc.})

You can probably make it a bit easier if the returned data has the same key names as your required types by doing:

res.data.map({name, capital} => {name, capital})

I guess it makes sense if you don't want to store dozens of other keys that you don't need in memory.

CodePudding user response:

With a rest api you can just ignore whatever you don’t need. There are alternatives for requesting specific information that is needed, such as GraphQL. Rest API can’t do that unless the server route is setup to return the info you need.

  • Related