How to Fix cannot find module and its corresponding type declarations

Cannot find module and its corresponding type declarations error typically occurs when using TypeScript with Node.js or frontend frameworks like Angular, React, or Vue. The main reason for the error is when TypeScript cannot find the type definitions for a particular module you are trying to import.

Simple diagram describing the error and solution

Simple diagram describing the error and solution.drawio

Solution 1: Install @types/react-leaflet

To fix the error, install the @types/react-leaflet package.

npm install @types/react-leaflet

Similarly, for other libraries, use the below command structure:

npm install @types/your_library_name

Now this will help solve this error. Let’s look at the second solution now.

Solution 2: Creating a decs.d.ts file

If you create a decs.d.ts file in the root folder of your project with module name declaration, this can lead to the fix of your error. In this case, I am declaring the react-leaflet module in the decs.d.ts file as:

declare module ‘react-leaflet’

Similarly, for other libraries, use the below module structure:

declare module ‘LibraryName’

The decs.d.ts file is used to fix the “cannot find module ‘react’ and its corresponding type declarations” error. Let us look at the 3rd solution to fix the error:

Solution 3: Using @ts-ignore

This is yet another method using which we can fix the mentioned error. By using @ts-ignore, we can fix the error. We can use this as follows:

// @ts-ignore 
import Map from 'react-leaflet'

Solution 4: Check tsconfig.json

Ensure that your tsconfig.json is correctly set up. Specifically, check the compilerOptions to ensure the moduleResolution is set to node and the types and typeRoots properties are correctly configured.

{
  "compilerOptions": {
    "moduleResolution": "node",
    "typeRoots": [
      "./node_modules/@types",
      "./types"
    ],
   "types": []
  }
}

Solution 5: Check Import Path

Ensure that the import path in your TypeScript file is correct. Sometimes, a simple typo or incorrect path can lead to this error.

Solution 6: Node Built-In Modules

If you’re trying to use a Node built-in module (like fs or path) in a frontend project, TypeScript might not recognize them by default. In such cases, you might need to install @types/node:

npm install @types/node

Solution 7: Restart the TypeScript Server

Sometimes, the TypeScript language server might not pick up the newly installed types immediately. If using an IDE like Visual Studio Code, restart the TypeScript server by pressing Cmd + Shift + P (or Ctrl + Shift + P on Windows/Linux) and searching for “Restart TypeScript Server”.

If you provide more specific details about the module you’re facing issues with, I might be able to give more tailored advice.