在 TypeScript 中,.d.ts
文件是类型声明文件(Declaration Files),用于描述 JavaScript 库或模块的类型信息,但不包含具体实现。它们帮助 TypeScript 编译器进行类型检查,同时保持与纯 JavaScript 的兼容性。
.d.ts
文件的基本结构
1. 声明全局变量(适用于非模块化 JS 库)
// 声明全局变量
declare const myGlobalVar: string;
// 声明全局函数
declare function myGlobalFunc(name: string): void;
// 声明全局类
declare class MyGlobalClass {
constructor(value: number);
getValue(): number;
}
2. 声明模块(适用于 CommonJS/ES Modules)
// 声明一个模块(如第三方库)
declare module "some-library" {
export function doSomething(): void;
export const someValue: number;
}
3. 扩展已有模块(类型增强)
// 扩展 'express' 的 Request 类型
declare namespace Express {
interface Request {
user?: { id: string; name: string };
}
}
4. 声明类型/接口
// 自定义类型
type Point = { x: number; y: number };
// 接口声明
interface User {
id: number;
name: string;
email?: string; // 可选属性
}
常见用途
1、为无类型的 JS 库添加类型支持
例如:为旧版 jQuery 编写声明文件。
declare const $: {
(selector: string): JQuery;
ajax(url: string): Promise<any>;
};
2、描述模块导出
例如:为自定义模块 my-module
声明类型。
declare module "my-module" {
export function greet(name: string): string;
}
3、全局类型扩展
例如:在 window
上添加自定义属性。
interface Window {
myAppConfig: { debug: boolean };
}
生成 .d.ts
文件的方式
1、手动编写
-
适用于小型项目或补充缺失的类型声明。
2、使用 tsc
自动生成
-
在
tsconfig.json
中启用"declaration": true
,编译时会生成.d.ts
文件。
{
"compilerOptions": {
"declaration": true,
"outDir": "./dist"
}
}
3、通过 DefinitelyTyped 社区库
-
许多流行库的类型声明已发布到
@types/*
(如@types/react
)。
最佳实践
-
文件命名:与源码同名(如
index.js
→index.d.ts
)。 -
避免
any
:尽量提供精确类型,减少any
的使用。 -
模块化:使用
export
/import
替代全局声明(现代 TS 推荐方式)。