【问题标题】:how to set proper types in axios request for array of objects?如何在 axios 请求中为对象数组设置正确的类型?
【发布时间】:2021-09-21 12:56:17
【问题描述】:

我正在尝试为 api 请求编写 axios 服务,但我无法理解此错误:

类型“AxiosResponse”缺少以下属性 键入“用户 []”:长度、弹出、推送、连接和 26 个更多.ts(2740) const 响应:AxiosResponse

我的代码是这样的:

import axios from 'axios';
import User from 'src/models/User';

const http = axios.create({
  baseURL: process.env.API,
  headers: { 'Content-Type': 'application/json' },
});

export async function getAllUsers(): Promise<User[]> {
  const response = await http.get<User[]>('users/');
  return response;
}

export async function getSingleUser(itemId: string): Promise<User> {
  const response = await http.get<User>(`/${itemId}`);
  return response;
}

当然,我没有理解一些基本的打字稿概念。你能帮帮我吗?

如果响应将被包装在“数据”属性中,应该怎么做?

【问题讨论】:

    标签: javascript typescript axios


    【解决方案1】:

    您缺少的是 axios 函数(例如 get)返回 AxiosInstance 而不是您期望的实际对象这一事实。您应该访问 AxiosInstancedata 属性以获得您期望的值:

    export async function getAllUsers(): Promise<User[]> {
      const response = await http.get<User[]>('users/');
      return response.data;
    }
    

    【讨论】:

      【解决方案2】:

      您应该为http.get() 方法返回res.data,请参阅Response Schema

      import axios from 'axios';
      
      interface User {}
      
      const http = axios.create({
        baseURL: process.env.API,
        headers: { 'Content-Type': 'application/json' },
      });
      
      export async function getAllUsers(): Promise<User[]> {
        const response = await http.get<User[]>('users/').then(res => res.data)
        return response;
      }
      
      export async function getSingleUser(itemId: string): Promise<User> {
        const response = await http.get<User>(`/${itemId}`);
        return response;
      }
      

      TypeScript Playground

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-09-21
        • 2020-01-17
        • 1970-01-01
        • 2021-05-05
        • 1970-01-01
        • 2018-10-31
        • 2022-01-23
        • 2020-04-19
        相关资源
        最近更新 更多