【问题标题】:Specify axios response data type指定 axios 响应数据类型
【发布时间】:2021-05-06 11:59:17
【问题描述】:

我正在构建 API 以将我的 react 应用程序与我的后端服务连接起来,并且我想使用 typescript 在我的 Axios 请求中指定 data 的类型。如何在不修改其他字段的情况下更新 Axios 响应中的数据类型(参见下面代码中的 getAllProjects)?

class MyApi {
   constructor(token: string | null) {
     let headers: any = {
            'Content-Type': 'application/json',
     };
     if (token) {
        headers = {
          ...headers, //append other basic proprieties
          'Authorization': 'Token ' + token
        }
     }

     this.baseEndpoint = axios.create({
        baseURL: `${baseURL}`,
        headers: headers
     });

  }

  //DATA
  const getAllProjects = async () : Promise<AxiosResponse<?????>> => this.baseEndpoint.get('/projects/');
}

简单地分配所需的类型(在本例中假设data: string[])会引发以下错误:

Argument of type 'string[]' is not assignable to parameter of type 'SetStateAction<never[]>'.
  Type 'string[]' is not assignable to type 'never[]'.
    Type 'string' is not assignable to type 'never'.

【问题讨论】:

    标签: reactjs typescript axios


    【解决方案1】:

    试试

    export const getAllProjects = async () => backend.get<string[]>('/projects/')
    

    对于其他上下文,Axios 请求的类型如下:

    request<T = any, R = AxiosResponse<T>> (config: AxiosRequestConfig): Promise<R>
    

    AxiosResponse 被定义为

    export interface AxiosResponse<T = any>  {
      data: T;
      status: number;
      statusText: string;
      headers: any;
      config: AxiosRequestConfig;
      request?: any;
    }
    

    这允许他们采用通用类型参数,该参数可用于指定给定响应的data 属性的类型,如下所示:

    type Data = {
      A: string
      B: number
      C: boolean
      // Etc.
    }
    
    Axios.get<Data>(endpoint).then(response => {
      const { data } = response // Data
      data.a // string
      data.b // number
      data.c // boolean
    })
    

    【讨论】:

    • 谢谢,阿曼。我保存了您的答案,因为它是对我问题的正确回答。我犯的错误是我没有在 UI 中指定我的状态类型,并且问题与 Axios 类型无关。
    猜你喜欢
    • 2021-10-19
    • 2022-11-25
    • 2021-02-21
    • 2021-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-06
    • 2021-06-03
    相关资源
    最近更新 更多