Skip to main content

Declaration Files (.d.ts)

When you install an old JavaScript library from npm, it often doesn't have any types. Declaration files are how you bridge the gap between untyped JS and strict TS.

The mental model

A .d.ts (declaration) file is like a C++ header file. It contains absolutely zero executable code. It only contains the signatures of the code.

When you import a .js module, TypeScript looks for an accompanying .d.ts file to understand what variables and functions are exported from the JavaScript file.

// example.d.ts
// We declare the shape of the module without implementing it
declare module "old-math-lib" {
export function add(a: number, b: number): number;
export const PI: number;
}

DefinitelyTyped (@types)

The community maintains a massive repository of declaration files for popular JavaScript libraries called DefinitelyTyped.

If you npm install lodash and try to import it, TypeScript will complain that it can't find the module. You solve this by installing the community-provided declaration files: npm install --save-dev @types/lodash

TypeScript will automatically find these types inside node_modules/@types and apply them to your lodash imports.

Writing your own global declarations

Sometimes you need to type global variables injected by a script tag, or add properties to the global window object. You do this in a global.d.ts file included in your project.

// global.d.ts
interface Window {
// Tell TS that window.analyticsTracker is safely defined
analyticsTracker: {
trackEvent(name: string): void;
};
}

A .d.ts file describes the shape of JavaScript code to the TypeScript compiler. Rely on @types/ packages for third-party libraries, and write your own global.d.ts for environment-specific globals.