Fix - styled-components Could not find declaration file


Borislav Hadzhiev

Sat Feb 19 20222 min read


Photo by Ryan Cheng

Fix - styled-components Could not find declaration file #

The error "could not find declaration file for module 'styled-components'" occurs when TypeScript cannot find the type declaration for a styled-components-related module. To solve the error install the types for the module by running the command from the error message.

could not find declaration file styled components

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

npm i --save-dev @types/styled-components # 👇️ you only need this if using REACT-NATIVE npm i --save-dev @types/styled-components-react-native

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 style-components-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.

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:

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.

// 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.