Marcus Junius Brutus
Marcus Junius Brutus

Reputation: 27306

axios has no exported member 'CancelToken'

I am migrating a JavaScript codebase to TypeScript. In many source files I had:

import {CancelToken} from 'axios';

... and cancellation worked perfectly. Upon migrating to TypeScript I am getting:

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

Upon investigating, I see that file node_modules/axios/lib/axios.js (imported from axios/index.js) does indeed contain a named member CancelToken:

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

(and how could it be differntly since the Javascript version of the code worked). Weirdly, though, the exact same name is used for an interface type (found in node_modules/axios/lib/index.t.ds):

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

}

My questions are:

  1. how do I properly address or, failing that, get around this error?
  2. when, in my code, I do import {CancelToken} from 'axios' am I importing the object from axios/index.js or the interface from axios/index.d.ts? (I am assuming the former). Is there no clash / how can I make it unambiguous ?

update

Upon further experimenting I tried:
import {CancelToken} from './some/path/node_modules/axios/index.js';

... which got me a different message:

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

In my code I have:

const source = CancelToken.source();

... and it is for the above line that TypeScript is complaining that "[the] type [...] is being used as a value".

Upvotes: 2

Views: 5593

Answers (2)

Mikhail Vasin
Mikhail Vasin

Reputation: 2580

Try

import axios from 'axios'

const cancelToken = axios.CancelToken

Upvotes: 4

Marcus Junius Brutus
Marcus Junius Brutus

Reputation: 27306

I initially ended up doing:

import CancelToken from './some/path/node_modules/axios/lib/cancel/CancelToken.js';

... which seems like a hack and I've no idea why it was necessary. A few days later I discovered a better way:

I set "moduleResolution": "node" in my "compilerOptions" structure in the tsconfig.json file and then used:

const {CancelToken} = require('axios');

Upvotes: 0

Related Questions