首页 > 解决方案 > axios 没有导出成员 'CancelToken'

问题描述

我正在将 JavaScript 代码库迁移到 TypeScript。在我拥有的许多源文件中:

import {CancelToken} from 'axios';

...并且取消工作完美。迁移到 TypeScript 后,我​​得到:

TS2305: Module '"./some/path/node_modules/axios/index.js"' has no exported member 'CancelToken'.

经过调查,我看到该文件node_modules/axios/lib/axios.js(从 导入axios/index.js)确实包含一个命名成员CancelToken

axios.CancelToken = require('./cancel/CancelToken');
...
module.exports = axios;

(自从代码的 Javascript 版本工作以来,它怎么可能有所不同)。奇怪的是,接口类型使用了完全相同的名称(在 中找到node_modules/axios/lib/index.t.ds):

export interface CancelToken {
  promise: Promise<Cancel>;
  reason?: Cancel;
 throwIfRequested(): void;

}

我的问题是:

  1. 我该如何正确解决,或者如果做不到这一点,如何解决这个错误?
  2. 什么时候,在我的代码中,我import {CancelToken} from 'axios'是从哪里导入对象axios/index.js还是从哪里导入接口axios/index.d.ts?(我假设前者)。没有冲突/我怎样才能使它明确?

更新

经过进一步的实验,我尝试了:
import {CancelToken} from './some/path/node_modules/axios/index.js';

...这给了我一个不同的信息:

TS2693: 'CancelToken' only refers to a type, but is being used as a value here

在我的代码中,我有:

const source = CancelToken.source();

...并且 TypeScript 抱怨“[the] type [...] is used as a value”是针对上述行的。

标签: typescriptaxios

解决方案


尝试

import axios from 'axios'

const cancelToken = axios.CancelToken

推荐阅读