What Declaration Files Are
You'll learn what .d.ts files do and why TypeScript needs them to work with JavaScript code.
The Fundamental Idea
A declaration file (.d.ts) is a special TypeScript file that contains only type information—no actual executable JavaScript code. It's like a blueprint or contract that tells TypeScript what types exist in corresponding JavaScript code, without providing the implementation.
Think of it this way: if JavaScript code is a book's content, a declaration file is its table of contents and index—it tells you what's inside and where to find it, but doesn't contain the actual story.
Why Declaration Files Exist
TypeScript needs to type-check your code, but much of the JavaScript ecosystem exists without types. Declaration files bridge this gap. They allow TypeScript to:
- Understand the shape of JavaScript libraries
- Provide autocomplete and IntelliSense for untyped code
- Catch type errors when calling JavaScript functions
- Work with legacy code during migration
What They Look Like
Unlike .ts files that compile to .js, declaration files:
- Have the
.d.tsextension - Contain type signatures without implementations
- Use the
declarekeyword to describe existing JavaScript - Never execute—they exist purely for the type checker
When You Encounter Them
You interact with declaration files whenever you:
- Install
@types/nodeor@types/reactfrom DefinitelyTyped - Use a library that ships with built-in types
- Generate them automatically with the
declarationcompiler option - Write custom types for untyped JavaScript libraries
Key Takeaway: Declaration files describe types without implementation, allowing TypeScript to type-check JavaScript code safely.