TypeScript Declaration Files (.d.ts)
Declaration files (.d.ts) are files that contain only type information and no implementation logic. They allow TypeScript to understand the shape and types of JavaScript code, enabling type checking and autocompletion for libraries written in plain JavaScript.
1. The Concept
Think of a .d.ts file as a "header file" in C/C++. It tells the compiler: "Trust me, a variable/function with this name and this shape exists at runtime."
- Extension:
.d.ts - Content:
interface,type,declare var,declare function,declare module, etc. - Output: These files are not compiled to
.js. They are used purely during development.
2. Consuming Type Definitions (@types)
Most popular JavaScript libraries (like React, Lodash, Express) do not include TypeScript definitions by default. Instead, the community maintains them in the DefinitelyTyped repository.
To get types for a library like lodash:
npm install lodash
npm install --save-dev @types/lodash
TypeScript automatically looks in node_modules/@types to find these definitions.
3. Writing Your Own Declaration Files
If you are using a library that doesn't have @types available, or you have local JavaScript files, you might need to write your own.
Scenario: A Global Variable
Suppose you have a script in your HTML that defines a global variable config.
// global.d.ts
declare var config: {
apiUrl: string;
retryCount: number;
};
Now you can use config.apiUrl in your TypeScript files without errors.
Scenario: A JavaScript Module
Suppose you have a file my-utils.js that exports functions but has no types. You can create my-utils.d.ts next to it.
// my-utils.d.ts
export declare function add(a: number, b: number): number;
export declare function subtract(a: number, b: number): number;
export declare interface User {
id: number;
name: string;
email?: string;
}
4. Module Augmentation
Sometimes you need to add properties to an existing library's types. For example, adding a user property to an Express Request object.
// custom-express.d.ts
import { Request } from 'express';
declare module 'express' {
interface Request {
user?: {
id: string;
role: string;
};
}
}
5. Generating Declaration Files
If you are writing a library in TypeScript and want to publish it for others to use, you should generate .d.ts files so consumers can benefit from your types.
In tsconfig.json:
"declaration": true