Could not find declaration file for 'styled-components'

avatar

Borislav Hadzhiev

Last updated: Feb 19, 2022

banner

Photo from Unsplash

Could not find declaration file for 'styled-components' #

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:

shell
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 to 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.

Conclusion #

The error "could not find a 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.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.