Using Typescript without definition files (error TS2307: Cannot find module) 🐞

If you are using less popular node packages, there is a high probability you will end up in situations where they don’t have definitions for Typescript created. Those definitions look like @types/someModuleName.

Without the definition file and the fact that Typescript won’t be able to resolve the module due to missing types, you will get the TS2307 error:

TSError: ⨯ Unable to compile TypeScript:
someFile.ts(some:line): error TS2307: Cannot find module 'some-module-without-definition-file'.

In such situations you can deal with the problem in two ways, either write the definition file yourself and do a pull request for that specific module or probably more realistic one, simply try to bypass the error and continue what you’ve been doing.

To fix this, go ahead and create a definition file somewhere in your project directory containing the name of the module, e.g. someModule.d.ts.

The next step is to actually declare the module inside of it

declare module 'module-name' {
  const x: any;
  export = x;
}

This will simply declare the missing definitions for that module and as you can see, export any type.

While this will fix your issue and you will proceed normally with your work, ideally you can keep this file filled and improved as you work, especially if the module you are using is occurring frequently in your code base. After all, you have decided to go with Typescript mainly because of its static nature, therefore, you want to avoid using any as much as possible.