💡 Problem: TypeScript Can’t Find Type Definitions
When using a JavaScript package in a TypeScript project, you might see:
sql
Could not find a declaration file for module 'XYZ'.
Try `npm install @types/XYZ` if it exists or add a new declaration (.d.ts) file containing `declare module 'XYZ';`
✅ Step 1: Check for Existing Type Definitions
TypeScript uses DefinitelyTyped for third-party types.
Try installing the types via npm:
bash
npm install --save-dev @types/XYZ
Replace XYZ
with the actual package name (e.g., lodash
→ @types/lodash
).
📌 Example:
bash
npm install --save lodash
npm install --save-dev @types/lodash
🧱 Step 2: No Types? Declare the Module Yourself
If @types/XYZ
does not exist, create a custom .d.ts
file to avoid compile errors.
🛠️ How to do it:
- In your project (usually in
src/
or a types/
folder), create a file:
bash
types/xyz.d.ts
- Add a simple module declaration:
ts
// types/xyz.d.ts
declare module 'xyz';
This tells TypeScript: "Hey, trust me, this module exists."
✨ Optional: Add Custom Type Definitions
If you know the package exports, you can define them more precisely:
ts
// types/xyz.d.ts
declare module 'xyz' {
export function doSomething(input: string): boolean;
export interface Options {
debug?: boolean;
}
}
🧠 Why This Matters
- Prevents build errors
- Enables IntelliSense/autocomplete
- Improves developer experience
- Maintains type safety
📁 Best Practice: Add a types/
Directory
In tsconfig.json
, ensure TypeScript picks up your custom types:
json
{
"compilerOptions": {
"typeRoots": ["./node_modules/@types", "./types"]
}
}