declaration: Generating .d.ts Files
What you'll learn: How to automatically create declaration files that let other TypeScript developers use your code with full type information.
What Are Declaration Files?
When you write TypeScript and compile it to JavaScript, the type information disappears from the final .js files. A declaration file (.d.ts) is like a "types-only" version of your code—it tells TypeScript users what types your functions accept and return, without containing any actual implementation.
Think of it like a restaurant menu: the menu lists what dishes are available and describes them, but it doesn't contain the recipes. Similarly, a .d.ts file describes your code's "interface" to the outside world.
Why This Matters
If you're building a library that others will install via npm, they need these declaration files to get autocomplete, type checking, and IntelliSense in their editors. Without .d.ts files, your TypeScript library would look like plain, untyped JavaScript to consumers.
Enabling Declaration Generation
In your tsconfig.json, add this to compilerOptions:
{
"compilerOptions": {
"declaration": true,
"outDir": "./dist"
}
}
Now when you run tsc, TypeScript will generate both .js files (the runnable code) and .d.ts files (the type definitions) in your output directory.
What Gets Generated
For every .ts source file you compile, TypeScript creates a matching .d.ts file containing only the exported types, interfaces, function signatures, and class shapes—no implementation code.
Key Takeaway: Enable "declaration": true in your tsconfig.json to generate .d.ts files alongside your JavaScript output, making your compiled code usable with full type safety by other TypeScript projects.