reactjs - 指定 axios 响应数据类型

标签 reactjs typescript axios

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

const generateApiInterface = ()=>{
    let headers: any= {
        'Content-Type': 'application/json',
    };
    if(token){
        headers={
            'Authorization': 'Token '+ token,
            ...headers //append other basic proprieties
        }
    }

    return axios.create({
        baseURL: baseURL,
        headers: headers
    });
}

const backend = generateApiInterface();

//DATA
export const getAllProjects = async () : Promise<AxiosResponse<?????>> => backend.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'.

最佳答案

尝试

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

关于reactjs - 指定 axios 响应数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66007441/

相关文章:

javascript - 如何将 this.props.children 传递给 Textarea

reactjs - React Semantic UI 中模态和下拉菜单的动画

javascript - 根据输入数据使用括号表示法

javascript - React Recharts 使用大量数据渲染阻塞

redux - 如何将数据添加到待处理操作?

javascript - 如何将 axios/AJAX 与 redux-thunk 结合使用

javascript - 为什么在 makeSquare(){...} 之前添加关键字函数会给我解析错误

javascript - 彩色交叉区域

typescript - 使嵌套类型的属性可选

javascript - Vue 和 Axios CORS 错误 No 'Access-Control-Allow-Origin' header is present on the requested resource