gpt4 book ai didi

javascript - axios 的 DefinelyTyped 问题

转载 作者:行者123 更新时间:2023-12-02 13:44:08 25 4
gpt4 key购买 nike

我已经使用 npm 和typings 安装了 axios。

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

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 接口(interface),那么“data: body”将被标记为错误。

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

最佳答案

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

安装 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);

关于javascript - axios 的 DefinelyTyped 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41533251/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com