TypeScript中统一设置axios的返回值类型

问题

const res = await request.post('/authorizations', values)
console.log(res.) //  这里的点没有提示

解决代码

// 泛型函数,接口,类
type ApiResponse<T> {
    message:string,
    data:T
  }
export const login = (values:any) => {
  return async (dispatch:any) => {
    const res = await request.post<ApiResponse<Token>>('/authorizations', values)
    dispatch({
      type: 'login/token',
      payload: res.data.data,
    })
  }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,让我们开始重构axios! 首先,我们需要安装TypeScript和相关的依赖。运行以下命令: ``` npm install typescript @types/node @types/qs @types/form-data ``` 接下来,我们需要创建一个tsconfig.json文件。在项目根目录下创建一个名为tsconfig.json的文件,并将以下内容复制到其: ```json { "compilerOptions": { "lib": ["es6", "dom"], "target": "es5", "module": "commonjs", "moduleResolution": "node", "declaration": true, "sourceMap": true, "outDir": "./dist", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true }, "exclude": ["node_modules"] } ``` 现在,我们可以开始重构axios的代码了。 首先,我们需要将axios的代码转换为TypeScript。我们可以将所有的JavaScript文件重命名为.ts文件,并使用TypeScript的语法更新代码。例如,我们可以使用类型注释来定义函数的参数类型返回类型。 下面是一个使用TypeScript语法重构的示例: ```typescript import * as http from 'http'; import * as https from 'https'; import * as url from 'url'; import * as zlib from 'zlib'; import { Cancel, CancelToken } from './cancel'; import { isFormData } from './utils'; import settle from './core/settle'; import buildURL from './helpers/buildURL'; import parseHeaders from './helpers/parseHeaders'; import createError from './core/createError'; import enhanceError from './core/enhanceError'; import defaults from './defaults'; interface AxiosRequestConfig { url?: string; method?: string; baseURL?: string; headers?: any; params?: any; data?: any; timeout?: number; withCredentials?: boolean; responseType?: XMLHttpRequestResponseType; xsrfCookieName?: string; xsrfHeaderName?: string; onDownloadProgress?: (progressEvent: any) => void; onUploadProgress?: (progressEvent: any) => void; cancelToken?: CancelToken; } interface AxiosResponse<T = any> { data: T; status: number; statusText: string; headers: any; config: AxiosRequestConfig; request?: any; } interface AxiosError<T = any> extends Error { config: AxiosRequestConfig; code?: string; request?: any; response?: AxiosResponse<T>; isAxiosError: boolean; } interface AxiosPromise<T = any> extends Promise<AxiosResponse<T>> {} interface Axios { defaults: AxiosRequestConfig; interceptors: { request: AxiosInterceptorManager<AxiosRequestConfig>; response: AxiosInterceptorManager<AxiosResponse>; }; request<T = any>(config: AxiosRequestConfig): AxiosPromise<T>; get<T = any>(url: string, config?: AxiosRequestConfig): AxiosPromise<T>; delete<T = any>(url: string, config?: AxiosRequestConfig): AxiosPromise<T>; head<T = any>(url: string, config?: AxiosRequestConfig): AxiosPromise<T>; options<T = any>(url: string, config?: AxiosRequestConfig): AxiosPromise<T>; post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): AxiosPromise<T>; put<T = any>(url: string, data?: any, config?: AxiosRequestConfig): AxiosPromise<T>; patch<T = any>(url: string, data?: any, config?: AxiosRequestConfig): AxiosPromise<T>; } interface AxiosInstance extends Axios { <T = any>(config: AxiosRequestConfig): AxiosPromise<T>; <T = any>(url: string, config?: AxiosRequestConfig): AxiosPromise<T>; } interface AxiosStatic extends AxiosInstance { create(config?: AxiosRequestConfig): AxiosInstance; CancelToken: CancelTokenStatic; Cancel: CancelStatic; isCancel: (value: any) => boolean; } interface AxiosInterceptorManager<T> { use(resolved: ResolvedFn<T>, rejected?: RejectedFn): number; eject(id: number): void; } interface ResolvedFn<T> { (val: T): T | Promise<T>; } interface RejectedFn { (error: any): any; } interface CancelToken { promise: Promise<Cancel>; reason?: Cancel; throwIfRequested(): void; } interface Canceler { (message?: string): void; } interface CancelExecutor { (cancel: Canceler): void; } interface CancelTokenSource { token: CancelToken; cancel: Canceler; } interface CancelTokenStatic { new (executor: CancelExecutor): CancelToken; source(): CancelTokenSource; } interface Cancel { message?: string; } interface CancelStatic { new (message?: string): Cancel; } function axios<T = any>(config: AxiosRequestConfig): AxiosPromise<T> { return dispatchRequest(config); } function createInstance(config: AxiosRequestConfig): AxiosInstance { const context = new Axios(config); const instance = Axios.prototype.request.bind(context); Object.assign(instance, Axios.prototype, context); return instance as AxiosInstance; } const axiosInstance = createInstance(defaults); axiosInstance.create = function create(config) { return createInstance(Object.assign(defaults, config)); }; function getDefaultAdapter() { let adapter; if (typeof XMLHttpRequest !== 'undefined') { adapter = require('./adapters/xhr'); } else if (typeof http !== 'undefined') { adapter = require('./adapters/http'); } else if (typeof https !== 'undefined') { adapter = require('./adapters/http'); } return adapter; } function dispatchRequest<T = any>(config: AxiosRequestConfig): AxiosPromise<T> { throwIfCancellationRequested(config.cancelToken); processConfig(config); return getDefaultAdapter()(config).then((response) => { return transformResponseData(response); }, (error) => { if (error && error.response) { error.response = transformResponseData(error.response); } return Promise.reject(error); }).then((response) => { settle(resolve, reject, response); return response; }, (error) => { settle(resolve, reject, enhanceError(error)); return Promise.reject(enhanceError(error)); }); } function processConfig(config: AxiosRequestConfig): void { config.url = transformURL(config); config.headers = transformHeaders(config); config.data = transformData(config); config.params = transformParams(config); } function transformURL(config: AxiosRequestConfig): string { const { url, params, baseURL } = config; return buildURL(url!, params, baseURL); } function transformHeaders(config: AxiosRequestConfig): any { const { headers = {}, data } = config; return Object.assign(headers.common || {}, headers[config.method!] || {}, headers, data ? data.headers : null); } function transformData(config: AxiosRequestConfig): any { const { data } = config; return isFormData(data) ? data : JSON.stringify(data); } function transformParams(config: AxiosRequestConfig): any { const { params } = config; return params ? params : null; } function transformResponseData(response: AxiosResponse): AxiosResponse { response.data = transformData(response); response.headers = parseHeaders(response.headers, response.config); response.data = transformData(response); return response; } function throwIfCancellationRequested(cancelToken?: CancelToken): void { if (cancelToken) { cancelToken.throwIfRequested(); } } export default axiosInstance; ``` 现在我们已经将axios的代码转换为了TypeScript,接下来我们需要更新一下项目的结构。 我们可以将所有的TypeScript代码放在一个src目录下,并将编译后的JavaScript代码放在一个dist目录下。这样做可以使我们的代码更加结构化和易于管理。 接下来,我们需要更新package.json文件的scripts字段,以便使用TypeScript编译我们的代码。在scripts字段添加以下内容: ```json "scripts": { "build": "tsc" } ``` 现在我们可以运行npm run build命令来编译我们的代码了。 最后,我们需要更新我们的引用代码,以便使用重构后的axios。例如,我们可以使用以下代码来发送一个GET请求: ```typescript import axios from './dist/axios'; axios.get('/user', { params: { ID: 12345 } }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); ``` 这就是使用TypeScript从零重构axios的过程。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值