Max Minin
Max Minin

Reputation: 483

Typescript: Ignore implicitly any type when importing js module

In Typescript project I need to import some old js files that do module.exports inside of themselves.

As i import:

import * as httpConnection from '...path...';

I got errors from compiler:

Could not find a declaration file for module '...path...'. '...path...' implicitly has an 'any' type.

After that it works OK, but i need to avoid this error in console.

How can I make compiler understand that import has any type without creating declaration file?

Thanks for ideas in advance.

Upvotes: 36

Views: 48303

Answers (3)

skantus
skantus

Reputation: 1033

You could create a file named: global.d.ts at the root of your project and add this:

declare module '*';

or you can ignore some specific imported libraries:

declare module 'name-of-the-lib';

Upvotes: 16

Viraj Singh
Viraj Singh

Reputation: 2329

followup on skantus answer, make sure you include the global.d.ts in tsconfig.json includes array,

// in tsconfig.json
 
 "include": [
    "src",
    "src/models/common/global.d.ts"
  ]

// in src/models/common/global.d.ts
declare module '*'; // this will ignore all the js import errors
declare module 'diagram-js'; // or instead of ignoring all, you can ignore specific modules like this

Upvotes: 5

dekajoo
dekajoo

Reputation: 2102

This mean you should type this module. Typescript is not happy with this module implicitly not having any definition file.

If it's an external public module you might just be able to install its types with a npm install @types/name_of_the_module

(Some modules even have their definition files inside the lib now. So just npm installing the module gives you the .d.ts definitions. But here that's probably not the case)

If it's private code or if you can't find it you could add a .d.ts file next to it that would ideally type all of its functions. If your willing to sacrifice typing because you don't have time to do it you can just have an explicit any type on the module with the following .d.ts

declare var name_of_the_module: any;

declare module "name_of_the_module" {
    export = name_of_the_module;
}

Edit:

As pointed out by @stsloth as for Typescript 2.6 you can also ignore the error completely by adding the line // @ts-ignoreabove the import.

Upvotes: 34

Related Questions