[typescript] Could not find a declaration file for module 'module-name'. '/path/to/module-name.js' implicitly has an 'any' type

I read how TypeScript module resolution works.

I have the following repository: @ts-stack/di. After compiling the directory structure is as follows:

+-- dist
¦   +-- annotations.d.ts
¦   +-- annotations.js
¦   +-- index.d.ts
¦   +-- index.js
¦   +-- injector.d.ts
¦   +-- injector.js
¦   +-- profiler.d.ts
¦   +-- profiler.js
¦   +-- providers.d.ts
¦   +-- providers.js
¦   +-- util.d.ts
¦   +-- util.js
+-- LICENSE
+-- package.json
+-- README.md
+-- src
¦   +-- annotations.ts
¦   +-- index.ts
¦   +-- injector.ts
¦   +-- profiler.ts
¦   +-- providers.ts
¦   +-- util.ts
+-- tsconfig.json

In my package.json I wrote "main": "dist/index.js".

In Node.js everything works fine, but TypeScript:

import {Injector} from '@ts-stack/di';

Could not find a declaration file for module '@ts-stack/di'. '/path/to/node_modules/@ts-stack/di/dist/index.js' implicitly has an 'any' type.

And yet, if I import as follows, then everything works:

import {Injector} from '/path/to/node_modules/@ts-stack/di/dist/index.js';

What am I doing wrong?

This question is related to typescript node-modules

The answer is


For anyone else reading this, try renaming your .js file to .ts

Edit: You can also add "allowJs": true to your tsconfig file.


I had the same issue using a node module with a react application written in typescript. The module was successfully installed using npm i --save my-module. It is written in javascript and exports a Client class.

With:

import * as MyModule from 'my-module';
let client: MyModule.Client = new MyModule.Client();

Compilation fails with the error:

Could not find a declaration file for module 'my-module'. 
'[...]/node_modules/my-module/lib/index.js' implicitly has an 'any' type.
  Try `npm install @types/my-module` if it exists or add a new declaration (.d.ts) file containing `declare module 'my-module';`

@types/my-module does not exist, so I added a my-module.d.ts file next to the one where my-module is imported, with the suggested line. I then got the error:

Namespace '"my-module"' has no exported member 'Client'.

The client is actually exported and works normally if I use it in a js app. Also, the previous message tells me that the compiler is looking in the right file (/node_modules/my-module/lib/index.js is defined in my-module/package.json "main" element).

I solved the issue by telling the compiler I do not care about implicit any, that is, I set to false the following line of the tsconfig.json file:

    "noImplicitAny": false,

Could not find a declaration file for module 'busboy'. 'f:/firebase-cloud- 
functions/functions/node_modules/busboy/lib/main.js' implicitly has an ‘any’ 
type.

Try `npm install @types/busboy` if it exists or add a new declaration (.d.ts) 
the file containing `declare module 'busboy';`

In my case it's solved: All you have to do is edit your TypeScript Config file (tsconfig.json) and add a new key-value pair as:

"noImplicitAny": false

If you're importing a third-party module 'foo' that doesn't provide any typings, either in the library itself, or in the @types/foo package (generated from the DefinitelyTyped repository), then you can make this error go away by declaring the module in a file with a .d.ts extension. TypeScript looks for .d.ts files in the same places that it will look for normal .ts files: as specified under "files", "include", and "exclude" in the tsconfig.json.

// foo.d.ts
declare module 'foo';

Then when you import foo it'll just be typed as any.


Alternatively, if you want to roll your own typings you can do that too:

// foo.d.ts
declare module 'foo' {
    export function getRandomNumber(): number
} 

Then this will compile correctly:

import { getRandomNumber } from 'foo';
const x = getRandomNumber(); // x is inferred as number

You don't have to provide full typings for the module, just enough for the bits that you're actually using (and want proper typings for), so it's particularly easy to do if you're using a fairly small amount of API.


On the other hand, if you don't care about the typings of external libraries and want all libraries without typings to be imported as any, you can add this to a file with a .d.ts extension:

declare module '*';

The benefit (and downside) of this is that you can import absolutely anything and TS will compile.


Check the "tsconfig.json" file for compilation options "include" and "exclude". If it does not exist, just add them by informing your root directory.

// tsconfig.json
{
  "compilerOptions": {
  ...
  "include": [
    "src", 
  ],
  "exclude": [
    "node_modules", 
  ]
}

I solved my silly problem just by removing the extension statement "*.spec.ts" from the "exclude", because when including the "import" in these files, there were always problems.


I've tried everything here, but for me it was a completely different issue: I had to remove from my *.d.ts any import statements:

import { SomeModuleType } from '3rd-party-module';

After removing the error went away...

Clarification: When we declare a module in a *.d.ts file, it's automatically picked up by the Typescript compiler as an ambient module (the one you don't need to import explicitly). Once we specify the import ... from ..., the file now becomes a normal (ES6) module, and hence won't be picked up automatically. Hence if you still want it to behave as an ambient module, use a different import style like so:

type MyType: import('3rd-party-module').SomeModuleType;

I was getting this too, had me baffled for a while, even with the module and types already installed and reloading my IDE several times.

What fixed it in my case was terminating terminal processes, removing node_modules, clearing the node package manager cache and doing a fresh install then re-loading the editor.


This way works for me:

1. add your own declaration in a declaration file such as index.d.ts(maybe under the project root)
declare module 'Injector';
2. add your index.d.ts to tsconfig.json
  {
    "compilerOptions": {
        "strictNullChecks": true,
        "moduleResolution": "node",
        "jsx": "react",
        "noUnusedParameters": true,
        "noUnusedLocals": true,
        "allowSyntheticDefaultImports":true,
        "target": "es5",
        "module": "ES2015",
        "declaration": true,
        "outDir": "./lib",
        "noImplicitAny": true,
        "importHelpers": true
      },
      "include": [
        "src/**/*",
        "index.d.ts",   // declaration file path
      ],
      "compileOnSave": false
    }

-- edit: needed quotation marks around module name


Simply you can import it using require as following code:

var _ = require('your_module_name');

TypeScript is basically implementing rules and adding types to your code to make it more clear and more accurate due to the lack of constraints in Javascript. TypeScript requires you to describe your data, so that the compiler can check your code and find errors. The compiler will let you know if you are using mismatched types, if you are out of your scope or you try to return a different type. So, when you are using external libraries and modules with TypeScript, they need to contain files that describe the types in that code. Those files are called type declaration files with an extension d.ts. Most of the declaration types for npm modules are already written and you can include them using npm install @types/module_name (where module_name is the name of the module whose types you wanna include).

However, there are modules that don't have their type definitions and in order to make the error go away and import the module using import * as module_name from 'module-name', create a folder typings in the root of your project, inside create a new folder with your module name and in that folder create a module_name.d.ts file and write declare module 'module_name'. After this just go to your tsconfig.json file and add "typeRoots": [ "../../typings", "../../node_modules/@types"] in the compilerOptions (with the proper relative path to your folders) to let TypeScript know where it can find the types definitions of your libraries and modules and add a new property "exclude": ["../../node_modules", "../../typings"] to the file. Here is an example of how your tsconfig.json file should look like:

{
    "compilerOptions": {
        "module": "commonjs",
        "noImplicitAny": true,
        "sourceMap": true,
        "outDir": "../dst/",
        "target": "ESNEXT",
        "typeRoots": [
            "../../typings",
            "../../node_modules/@types"
        ]
    },
    "lib": [
            "es2016"
    ],
    "exclude": [
        "../../node_modules",
        "../../typings"
    ]
}

By doing this, the error will go away and you will be able to stick to the latest ES6 and TypeScript rules.


If you need a quick fix, simply add this before the line of your import:

// @ts-ignore

You have to do is edit your TypeScript Config file (tsconfig.json) and add a new key-value pair as:

"noImplicitAny": false

For Example: "noImplicitAny": false, "allowJs": true, "skipLibCheck": true, "esModuleInterop": true, continue....


Here are two other solutions

When a module is not yours - try to install types from @types:

npm install -D @types/module-name

If the above install errors - try changing import statements to require:

// import * as yourModuleName from 'module-name';
const yourModuleName = require('module-name');

simple to fix you re is :

// example.d.ts
declare module 'foo';

if you want to declarate interface of object (Recommend for big project) you can use :

// example.d.ts
declare module 'foo'{
    // example
    export function getName(): string
}

How to use that? simple..

const x = require('foo') // or import x from 'foo'
x.getName() // intellisense can read this

Unfortunately it's out of our hands whether the package writer bothers with a declaration file. What I tend to do is have a file such index.d.ts that'll contain all the missing declaration files from various packages:

Index.ts:

declare module 'v-tooltip';
declare module 'parse5';
declare module 'emoji-mart-vue-fast';

Examples related to typescript

TS1086: An accessor cannot be declared in ambient context Element implicitly has an 'any' type because expression of type 'string' can't be used to index Angular @ViewChild() error: Expected 2 arguments, but got 1 Typescript: No index signature with a parameter of type 'string' was found on type '{ "A": string; } Understanding esModuleInterop in tsconfig file How can I solve the error 'TS2532: Object is possibly 'undefined'? Typescript: Type 'string | undefined' is not assignable to type 'string' Typescript: Type X is missing the following properties from type Y length, pop, push, concat, and 26 more. [2740] Can't perform a React state update on an unmounted component TypeScript and React - children type?

Examples related to node-modules

SyntaxError: Cannot use import statement outside a module What could cause an error related to npm not being able to find a file? No contents in my node_modules subfolder. Why is that? Node - was compiled against a different Node.js version using NODE_MODULE_VERSION 51 npm WARN enoent ENOENT: no such file or directory, open 'C:\Users\Nuwanst\package.json' Cannot find the '@angular/common/http' module How to use paths in tsconfig.json? Could not find a declaration file for module 'module-name'. '/path/to/module-name.js' implicitly has an 'any' type How to fix 'fs: re-evaluating native module sources is not supported' - graceful-fs How to provide a mysql database connection in single file in nodejs Git - Ignore node_modules folder everywhere