要给出包含数组的 API 响应的 TypeScript 声明,可以使用 TypeScript 的接口(interface)来定义响应的结构。下面是一个示例:
interface ApiResponse {
  data: {
    items: Array<{
      id: number;
      name: string;
      description: string;
    }>;
    totalCount: number;
  };
  status: number;
  message: string;
}
在上面的示例中,ApiResponse 接口定义了一个包含数组的 API 响应的结构。响应的 data 字段是一个对象,包含了 items 数组和 totalCount 字段。items 数组的每个元素都是一个对象,包含了 id,name 和 description 字段。
你可以根据实际情况修改接口的字段和类型。如果响应中还包含其他字段,可以继续在接口中添加。
使用这个接口时,你可以将 API 响应的类型声明为 ApiResponse,然后使用它来标注 API 响应的变量或函数参数,以确保类型安全性。示例如下:
function processApiResponse(response: ApiResponse) {
  // 在这里处理 API 响应
}
const apiResponse: ApiResponse = {
  data: {
    items: [
      { id: 1, name: 'Item 1', description: 'Description 1' },
      { id: 2, name: 'Item 2', description: 'Description 2' },
    ],
    totalCount: 2,
  },
  status: 200,
  message: 'Success',
};
processApiResponse(apiResponse);
在上面的示例中,processApiResponse 函数接受一个类型为 ApiResponse 的参数,并在函数体内处理这个 API 响应。apiResponse 变量是一个符合 ApiResponse 类型的对象。
这样,TypeScript 将会在编译时进行类型检查,确保你在处理 API 响应时使用了正确的字段和类型,并提供了代码提示。
下一篇:包含数组的编号方程