Typescript has made it easy to locate errors, but most time QuickFix doesn't work. The error Could not find a declaration file for module 'Module Name' often happens when you start typescript. This is because typescript couldn't find the type deceleration for a react-related module. Don't panic it is easy to solve. Let's jump on it
This is what the error message looks like in the terminal and these are ways to solve it.
- Install the @type package for the module
// Installing the type module with npm
npm install @type/Module-Name
// Installing the type module for react-dom with npm
npm install @type/react-dom
// Installing the type module with npm
npm install @type/react-reveal
On the other hand, the error below might pop up when npm could not find the type of the module you are trying to install.
If you fall into this error, that the module you are trying to install doesn't provide typing. So let's discuss another way of fixing this.
- Using a .d.ts files
What are .d.ts files? These are declaration files that contain only type information. They are only used for checking types and typescript read them the same way it does with the regular .ts file which is mostly determined by the Include and Exclude setting in the tsconfig.json file
So create a .d.ts file in your project file inside your project file, it can have any name you want like the react-reveal.d.ts file (mostly use the module name), let's continue. Inside the file, you need to declare the module like this.
declare module 'module-name'
Make sure you change the module name to the module you are trying to fix the error. In most cases, this fixes the error because, with this, typescript automatically set the module type of any and the code should work fine.
In some cases, we might want to set the type ourselves, if you want to set the type you can just can this to your code
declare module 'module-name' {
export function myFunction(): string
}
Unfortunately, if the error isn't clear, we might have another option to fix it,
- Adding the eslint-disable next line comment
You can easily resolve the error by adding the eslint-disable next line comment to ignore the error on the code and allow your typescript to run perfectly without error
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
import { myFunction } from 'module-name';
// Example
import { Bounce } from "react-reveal";
So, with any of these solution Typescript Could not find declaration file for module 'react' can be fix.
If you like the article and it would be beneficial, please like and share for friends to they can benefit.
Thank you
Top comments (3)
Thanks for the heads up luke
That was a good read, thank you, followed and bookmarked!
Thank you Al-Naubit