Search code examples
typescriptaxiosnock

How to add type definitions for module in subdirectory?


I am trying to mock requests made with axios using nock. This integration has some issues historically, but the workaround described in this issue works. My issue occurs when I introduce Typescript into the mix. While axios comes with type definition files for the main library, the nock and axios integration requires an import from a subdirectory like so:

import HttpAdapter from 'axios/lib/adapters/http';

The Typescript compiler complains about this line with the following error:

TS7016: Could not find a declaration file for module 'axios/lib/adapters/http'. 'C:/Users/<user>/<project>/node_modules/axios/lib/adapters/http.js' implicitly has an 'any' type.
  Try `npm install @types/axios` if it exists or add a new declaration (.d.ts) file containing `declare module 'axios';`

How can I fix this error? I have tried various combinations of custom type definitions for axios resembling:

// <project>/src/types/axios.d.ts

declare module 'axios/lib/adapters/http` {
    import { Adapter } from 'axios';

    const HttpAdapter: Adapter;

    export default HttpAdapter;
}

I am not very experienced with Typescript, so my theories are that my custom definitions file is in the wrong place, uses the wrong module name, or is not exporting the correct thing. Any help would be greatly appreciated.


Additional Context

Typescript Version: 2.9.2

The (relevant) contents of tsconfig.json:

{
  "compilerOptions": {
    "allowSyntheticDefaultImports": true,
    "module": "esnext",
    "target": "es5",
    "lib": ["es2015", "es2017", "dom"],
    "moduleResolution": "node",
    "rootDir": "src",
    "noImplicitAny": true,
    "typeRoots": ["./src/types", "./node_modules/@types"]
  }
}

Solution

  • Add the types directory under the files/include like the rest of your TS files. Assuming all of the source files are in src, this should work:

    {
      "compilerOptions": {
        "allowSyntheticDefaultImports": true,
        "module": "esnext",
        "target": "es5",
        "lib": ["es2015", "es2017", "dom"],
        "moduleResolution": "node",
        "rootDir": "src",
        "noImplicitAny": true
    
        // This is automatically done by "moduleResolution": "node"
        // "typeRoots": ["./node_modules/@types"]
      },
    
      // Also make sure to add any other directories as needed
      "include": ["src/**/*"]
    }