I have a project create with CRA typescript.
at the root of project there exists tsconfig.json
and a folder called types
. at the types folder I have created a modulename.d.ts
file for a module that does not have default typings at node_modules and also there is nothing for it at @types\module-name
.
but I get the error at compile time.
Type error: Could not find a declaration file for module 'thename'. '/*/node_modules/thename/dist/entry.js' implicitly has an 'any' type.
why the compiler does not find the type declaration at types folder?
// .d.ts
declare module 'foo-react' {
import * as React from 'react';
// ...
}
this is the tsconfig.json
{
"compilerOptions": {
"baseUrl": ".",
"paths": { "*": ["types/*"] },
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"plugins": [{ "name": "typescript-tslint-plugin" }],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "preserve"
},
"include": ["src"]
}
The error "could not find a declaration file for module 'react'" occurs when TypeScript cannot find the type declaration for a react-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/react .
To solve the "Module not found: Can't resolve" error in React, make sure to install the package from the error message if it's a third-party package, e.g. npm i somePackage . If you got the error when importing local files, correct your import path.
The "Cannot find module or its corresponding type declarations" error occurs when TypeScript cannot locate a third-party or local module in our project. To solve the error, make sure to install the module and try setting moduleResolution to node in your tsconfig. json file.
Try `npm install @types/XYZ` if it exists or add a new declaration (. d. ts) file containing `declare module 'XYZ'; If XYZ is a direct dependency of your project, you can follow the instructions from the error message and run npm install @types/XYZ .
So it turned out that
@types
@types
folder (my customized one at the root of the project) should be added to types
attribute and not the paths
attribute. "types":["./@types"]
@types
folder having a structure like @types/<module_name>/index.d.ts
or @types/moduleName.d.ts
. Now the file can declare that module as any
or declare all types in detail.definition for types compiler option in Typescript handbook
--types string[] List of names of type definitions to include. See @types, —typeRoots and —types for more details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With