Search code examples
javascriptreactjstypescript

How to use TypeScript types on API response data


So I make a call to the api and return data from it. It contains way more data than I need, so I map trough my response and return only the values that I need. The problem is that I do not understand how to define my response data in TS. Now it looks like this but I know that using any is a bad option.

data = data.results.map((item: any) => {
                        return {
                            id: item.id,
                            src: item.urls.small,
                            description: item.alt_description,
                            name: item.user.name,
                            favorited: false
                        }
                    })

How should I transform response data to format that I need using TS. I think I need some additional step so I could use my interface on item.

interface PhotoModel {
    id: string
    src: string
    description: string
    name: string
    favorited: boolean
}

Solution

  • You need to create some interface or type that will describe the data you're going to process. For example:

    
    interface ResultItem {
      id: string;
      urls: {
        small: string;
      };
      alt_description: string;
      user: {
        name: string;
      };
    }
    
    interface PhotoModel {
      id: string
      src: string
      description: string
      name: string
      favorited: boolean
    }
    
    data.results.map((item: ResultItem): PhotoModel => {
        return {
            id: item.id,
            src: item.urls.small,
            description: item.alt_description,
            name: item.user.name,
            favorited: false
        }
    })
    
    

    However (especially if you don't control the shape of the API you're requesting), in runtime you might not get what you expect to get. So it would be beneficial to validate the data returned from the API first (for example, using some tool like io-ts or a similar one).