axios在ts下的封装报错ts(7052)

hellorayza
  • 23
import axios from 'axios';
import {Method} from 'axios'
let axiosIns = axios.create({
  timeout: 15000,
});
const requestType = ['get', 'post', 'delete', 'put'];
interface requestObj {
  [x: string]: any;
}
let request:requestObj={};

requestType.forEach((method:Method | string) => {
  request[method] = function (uri:string, data:any) {
    return new Promise(function (resolve, reject) {
      axiosIns[method](uri, data)
        .then((response:any) => {
          resolve(response);
        })
        .catch((err:any) => {
          reject(err);
        });
    });
  };
});

axiosIns[method]会报错:

Element implicitly has an 'any' type because type 'AxiosInstance' has no index signature. Did you mean to call 'axiosIns.get'?ts(7052)

这里应该怎么写好呢?
如果method:string换成method:Method呢?
另外requestType改成枚举呢?

回复
阅读 540
2 个回答
✓ 已被采纳
type MethodNames = Extract<Method, keyof AxiosInstance>;
const requestType: MethodNames[] = ["get", "post", "delete", "put"];

...

requestType.forEach((method: MethodNames) => { ... }
type Method = "get" | "delete" | "head" | "options" | "post" | "put" | "patch" | "GET" | "DELETE" | "HEAD" | "OPTIONS" | "POST" | "PUT" | "PATCH" | "purge" | "PURGE" | "link" | "LINK" | "unlink" | "UNLINK"
type Keys = keyof AxiosInstance;
// "defaults" | "interceptors" | "getUri" | "request" | "get" | "delete" | "head" | "options" | "post" | "put" | "patch"

Method不是axiosIns的实例属性啊,所以类型校验当然不通过。
这样写试试

import axios from "axios";
let axiosIns = axios.create({
  timeout: 15000
});
const requestType: Array<keyof typeof axiosIns> = ["get", "post", "delete", "put"];
interface requestObj {
  [x: string]: any;
}
let request: requestObj = {};

requestType.forEach((method) => {
  request[method] = function (uri: string, data: any) {
    return new Promise(function (resolve, reject) {
      (axiosIns[method] as CallableFunction)(uri, data)
        .then((response: any) => {
          resolve(response);
        })
        .catch((err: any) => {
          reject(err);
        });
    });
  };
});
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
你知道吗?

宣传栏