【问题标题】:Issue with the DefenitelyTyped of axiosaxios 的 DefenitelyTyped 问题
【发布时间】:2017-05-22 20:13:08
【问题描述】:

我已经安装了带有 npm 和 typings 的 axios。

现在,要在 TypeScript 中使用它,我需要向它传递一个类型 (T)。问题是这个T同时用于请求的接口和响应的接口,这没有任何意义,因为很明显服务器不会返回它接收到的相同类型的数据。

interface ServerRepsonse {
    userID: string;
}

interface ServerRequest {
    username: string;
    password: string;
}

var body = {
        username: "username",
        password: "password"
    };

let response = await axios<ServerRequest>({
            method: 'POST',
            url: "http://localhost:3000/users",
            data: body
        });

alert(response.data.userID);

如您所见,在此示例中,reponse.data.userID 将被标记为错误。如果我改为传递 ServerResponse 接口,则“data: body”将被标记为错误。

这是 axios 的 index.d.ts 文件的问题吗?我该如何解决?我不想使用“任何”。

【问题讨论】:

  • 不使用axios project中包含的定义文件有什么原因吗?

标签: javascript generics typescript axios definitelytyped


【解决方案1】:

目前的实现似乎没有完全使用泛型。但是你可以扩展它。

安装 axios 类型
npm i @types/axios

然后用

创建一个文件typings\axios.d.ts
declare namespace Axios {
  interface AxiosInstance {
    <TRequest, TResponse>(config: AxiosXHRConfig<TRequest>): IPromise<AxiosXHR<TResponse>>;
    post<TRequest, TResponse>(url: string, data?: TRequest, config?: AxiosXHRConfigBase<TResponse>): IPromise<AxiosXHR<TResponse>>;
  }
}

这将允许您使用:

import * as axios from 'axios';

interface DataToSend {
    name: string;
}
interface DataToReceive {
    status: number;
}

axios<DataToReceive>({ url: '' }).then(r => r.data.status);

axios<DataToSend, DataToReceive>({
    url: '',
    method: 'POST',
    data: { name: '' },
}).then(r => r.data.status);

axios.post<DataToSend, DataToReceive>('', { name: 'test' })
    .then(r => r.data.status);

【讨论】:

    猜你喜欢
    • 2017-03-05
    • 2019-12-29
    • 1970-01-01
    • 2018-11-29
    • 2019-05-11
    • 2020-08-24
    • 2019-08-18
    • 2020-09-15
    • 2021-03-28
    相关资源
    最近更新 更多