Declaration Files (.d.ts)
Typing pure JavaScript code.
The Type Overlay
A declaration file (.d.ts) is a TypeScript file that contains only type information—no actual executable JavaScript code.
It acts as a "type overlay" or a blueprint that describes the shape of pure JavaScript code to the TypeScript compiler.
The Untyped Wild West
If you install a pure JavaScript library (like an old version of lodash) and try to import it, TypeScript will throw an error because it has no idea what functions exist inside that library.
By creating a .d.ts file, you can "ambiently declare" the types for that library, allowing you to use it safely in TypeScript.
Syntax
typescript
// In a file named 'global.d.ts'
// 1. Typing a missing JS module
declare module "untyped-lib" {
export function doMagic(input: string): number;
}
// 2. Typing a global window variable
declare global {
interface Window {
ANALYTICS_ID: string;
}
}
Try it
See how an ambient declaration file bridges the gap between an untyped JavaScript module and a strict TypeScript consumer.
return str.length;
}
export function doMagic(input: string): number;
}
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
.d.tsfiles contain ONLY types. No executable code.- Use
declare module "name"to type a missing NPM package. - Use
declare globalto add types to thewindowobject. - Always check for
@types/package-namebefore writing your own!
Done with this concept?
Mark it complete to track your progress. No login needed.