.d.ts Declaration Files
In this page:
What Is a Declaration File
A .d.ts declaration file describes the shape of a library's types — its functions, classes, and variables — without containing any actual runtime implementation, letting TypeScript type-check code that calls into plain JavaScript.
Example: What Is a Declaration File
// math-lib.d.ts (no runtime code, only shapes)
declare function add(a: number, b: number): number;
// The real implementation lives in math-lib.js
console.log("Declaration file describes add() without implementing it");
Ambient Declarations
Ambient declarations (using the declare keyword) tell the compiler that something exists at runtime — like a global variable injected by a script tag — even though TypeScript can't see where it's actually defined.
Example: Ambient Declarations
declare const APP_VERSION: string;
// Assume a <script> tag defines APP_VERSION globally at runtime.
console.log("Ambient declaration for a global injected elsewhere");
Declaring Classes
Declaring a class in a .d.ts file lists its constructor signature, public members, and their types so consumers get autocomplete and type-checking against a class whose real implementation lives in a separate .js file.
Example: Declaring Classes
declare class EventEmitter {
on(event: string, handler: Function): void;
emit(event: string): void;
}
// Real implementation lives in a separate .js file.
console.log("Class shape declared for a JS implementation");
Declaring Functions
Declaring a function's signature in a .d.ts file — its parameter types and return type — is enough for the compiler to catch misuse at call sites, even without seeing a single line of that function's actual logic.
Example: Declaring Functions
declare function parseCsv(input: string): string[][];
// Only the signature is known here, not the logic.
console.log("Function signature declared, catches misuse at call sites");
When Declaration Files Are Used
Declaration files are typically used when shipping a JavaScript library to TypeScript consumers, when writing types for a global script that isn't a module, or when the DefinitelyTyped project hasn't yet published types for a package.
Example: When Declaration Files Are Used
// Used when: shipping a JS library, typing a global script,
// or DefinitelyTyped hasn't published types yet.
declare function legacyWidget(id: string): void;
console.log("Declaration files bridge JS libraries into TypeScript");
Chapter Quiz — Complete all 5 topics to unlock
0/5 topics done
Complete these topics first: