Fix - Could not find declaration file for module 'lodash'

avatar

Borislav Hadzhiev

Sat Feb 19 20222 min read

banner

Photo by Bevis G

Fix - Could not find declaration file for module 'lodash' #

The error "could not find declaration file for module 'lodash'" occurs when TypeScript cannot find the type declaration for a lodash-related module. To solve the error install the types for the module by running the command from the error message, e.g. npm install -D @types/lodash.

could not find declaration file lodash

The error message shows the command that you should try to run when you get the error. The command in the screenshot above is:

shell
npm i --save-dev @types/lodash

Usually the names of type packages are consistent - @types/module-name, but you could try to look for a definition package by using the official TypeScript type search.

If the error persists, the lodash-related, third-party module you are importing might not provide typings, which means that you need to declare the module in a file with a .d.ts extension.

TypeScript looks for .d.ts files in the same places it looks for your regular .ts files, which is determined by the include and exclude settings in your tsconfig.json file.

Create a new file named module-name.d.ts next to your regular TypeScript files and add the following line in it.

module-name.d.ts
declare module 'module-name';

Make sure to replace module-name with the name of the module that's causing the error.

This will set the type of the package to any when importing it. This should be sufficient for most use cases.

If you want to add your own type definitions for the package, replace the line with the following code:

module-name.d.ts
declare module 'module-name' { export function myFunction(): string; }

The example shows how to add types for a function named myFunction that returns a string.

You only need to add type definitions for the functions you intend to import in your code.

If this still doesn't work, you should try to ignore the error by adding the following lines above the import.

index.ts
// eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore import { myFunction } from 'module-name';

Adding these lines above the import statement will suppress the error message.

Use the search field on my Home Page to filter through my more than 1,000 articles.