How to use TypeScript types on API response data

Ste*_*pas 13 javascript typescript reactjs

So I make a call to the api and return data form it. It contains way more data than I need, so I map trough my response and return only 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
                        }
                    })
Run Code Online (Sandbox Code Playgroud)

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
    }
Run Code Online (Sandbox Code Playgroud)

fal*_*sky 7

您需要创建一些接口或类型来描述您要处理的数据。例如:


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
    }
})

Run Code Online (Sandbox Code Playgroud)

但是(特别是如果您不控制所请求的 API 的形状),在运行时您可能无法获得预期的结果。因此,首先验证从 API 返回的数据是有益的(例如,使用io-ts或类似工具)。