How to install @types for all node modules automatically

Viewed 10979

I am new to Typescript and NodeJs. Whenever I mention a node module in package.json and while importing the the node module, I always get the following errors.

Could not find a declaration file for module 'ini'. 'e:/typescript-2020-1/parser1/node_modules/ini/ini.js' implicitly has an 'any' type.
  Try `npm install @types/ini` if it exists or add a new declaration (.d.ts) file containing `declare module 'ini';`

  Could not find a declaration file for module 'json-query'. 'e:/typescript-2020-1/parser1/node_modules/json-query/index.js' implicitly has an 'any' type.
  Try `npm install @types/json-query` if it exists or add a new declaration (.d.ts) file containing `declare module 'json-query';`

To solve this problem, I always search and install the followings in package.json as given below.

"dependencies": {
        "ini": "^1.3.5",
        "@types/ini": "^1.3.30",
        "json-query": "^2.2.2",
        "@types/json-query": "^2.2.0"
        "@types/node": "^13.9.0"
    }

How to avoid inclusion of all types of node modules specific types. Is it possible to do in a way that @types/<node module> will be added automatically inside node_modues without directly adding to package.json? I tried to add the following in tsconfig.json also, but it is not working.

"typeRoots": [
            "node_modules/@types"
        ],

Again my question is "Is it always necessary to add @types for each and every node modules ? Please help me to solve it.

1 Answers

If an npm package contains types, you will get them for free when you install.

If not, then you may be able to find them under the @types namespace on npm.

There is a useful tool called typac that you can install or run via npx that will try to install the @types for your package when you use it to install any npm package.

i.e.

    npx typac ini -i  
Related