Declaration files
| What .d.ts is | |
| Generate with declaration | |
| Hand-written ambients | |
| DefinitelyTyped concept |
What .d.ts is
A declaration file holds only types: function signatures, interfaces, and constants with no bodies. Consumers type check against it without ever seeing the implementation.
Think of it as a header for the module. It is small, fast to load, and safe to share with every user of the package.
export function formatDate(value: Date): string;
export interface User {
name: string;
age: number;
}
Generate with declaration
Libraries rarely write these files by hand. The compiler generates them from the sources during the build, so types and code can never drift apart.
Turn the flag on once and every build emits JavaScript plus matching type files side by side.
tsc --declaration
app.js and app.d.ts are written
Hand-written ambients
Plain JavaScript libraries have no types to generate. A hand-written ambient file describes the global or module shape so TypeScript can check calls into it.
Declare only what you use. A ten line ambient for two functions beats a full rewrite that nobody will maintain.
declare function formatPrice(cents: number): string;
declare const APP_VERSION: string;
DefinitelyTyped concept
Popular JavaScript packages share community maintained declarations in one large public collection. When a library ships no types, the collection often has them already.
The idea is simple: one place for widely reused ambient types, reviewed in the open. Your project then type checks third party calls like first party code.
import { formatPrice } from "payments";
const label = formatPrice(1999);
console.log(label);
Next: Linting
Article author: Arthur Isaev