What Are Declaration Files (.d.ts)
You'll learn what declaration files are and why TypeScript uses them to describe JavaScript code without including any implementation.
The Core Idea
A declaration file (with a .d.ts extension) is a special TypeScript file that contains only type information—no actual JavaScript code or logic. Think of it as a blueprint or a map that tells TypeScript what types exist in JavaScript code, without showing how that code actually works.
If regular TypeScript files (.ts) are like recipes with both ingredients lists and cooking instructions, declaration files are like ingredient labels that describe what's in the package without explaining how it was made.
Why They Exist
Declaration files solve a fundamental problem: JavaScript code has no type information. When you use a JavaScript library, TypeScript has no idea what types its functions accept or return. Declaration files bridge this gap by providing type-only descriptions of JavaScript code.
Type Descriptions Without Implementation
Here's the key distinction: declaration files declare types but provide no runtime logic. They tell the compiler "this function exists and has this signature" without implementing the function itself.
A declaration file might say: "There's a function called parseJSON that takes a string and returns an object"—but it won't include the actual parsing logic. That logic lives in the JavaScript file.
Common Sources
You encounter declaration files in three main scenarios:
- Third-party JavaScript libraries ship declaration files so TypeScript users get type safety
- Your own compiled TypeScript can generate declaration files for consumers of your code
- The DefinitelyTyped project provides community-maintained declaration files for popular JavaScript libraries
Key Takeaway: Declaration files (.d.ts) are type-only files that describe the shape and types of JavaScript code without containing any implementation, enabling TypeScript to provide type safety when working with JavaScript libraries.