TypeScript 类型声明文件:.d.ts 文件编写
TypeScript 类型声明文件(.d.ts)的作用是为 JavaScript 代码提供类型信息,让编辑器能够提供智能提示和类型检查。编写高质量的声明文件是维护大型项目和开发公用库的关键技能。
1. 理解声明文件基础
声明文件仅包含类型声明,不包含具体的逻辑实现。它的核心任务是描述变量、函数、类或模块的“形状”。
-
创建 一个名为
types.d.ts的文件。文件名通常任意,但后缀必须为.d.ts。 -
编写 最基础的声明语句。例如,声明一个全局变量:
declare let userName: string; declare function getUser(id: number): string; -
查看 声明合并规则。声明文件支持多次声明同一个对象,TypeScript 会自动合并。
2. 编写全局变量声明
对于通过 <script> 标签引入的第三方库,通常需要声明全局变量。
-
使用
declare var或declare let声明变量。如果变量是只读的,使用declare const。 -
定义 变量的类型。
// 声明一个名为 myApp 的全局对象 declare const myApp: { version: string; start: () => void; }; -
注意 命名冲突。确保声明的变量名不会与全局作用域中已有的变量名冲突,除非是有意进行声明合并。
3. 编写函数与对象声明
函数和对象是 JavaScript 中最常见的类型,声明文件需要精确描述它们的结构。
-
使用
declare function声明函数。支持函数重载,即声明多个不同参数列表的同名函数。 -
编写 函数签名。
// 函数重载:根据参数类型返回不同类型的数据 declare function parseInput(input: string): string[]; declare function parseInput(input: number): number[]; -
使用
interface或type定义复杂的对象结构。这比直接内联写对象字面量更清晰,且可复用。interface AppConfig { apiUrl: string; timeout: number; } declare const config: AppConfig;
4. 处理模块与导出
现代前端开发普遍使用模块化(ES Modules 或 CommonJS),声明文件需要正确处理 import 和 export。
-
识别 模块类型。如果文件顶层包含
export关键字,该文件就是一个模块,而不是全局声明文件。 -
使用
export导出类型。// utils.d.ts export function log(message: string): void; export interface User { id: number; name: string; } -
编写 声明文件为 CommonJS 模块。如果库使用
module.exports = ...语法,需要使用export =语法。// lib.d.ts declare function hello(name: string): void; export = hello;
5. 为第三方库编写声明
当使用的 JavaScript 库没有自带类型声明,也没有 @types/xxx 包时,需要手动编写声明文件。
-
创建
declarations.d.ts或具体的文件名(如library-name.d.ts)。 -
使用
declare module语法声明模块。这是最快捷的方式,适用于暂时不需要详细类型检查的情况。declare module 'legacy-library' { const content: any; export default content; } -
扩展 全局命名空间。如果库扩展了原生对象(如
String原型),需要在声明文件中合并到全局接口。declare global { interface String { reverse(): string; } }
6. 利用工具自动生成
手动编写声明文件容易出错,TypeScript 编译器提供了自动生成功能。
-
打开 项目根目录下的
tsconfig.json文件。 -
设置
declaration选项为true。这会指示编译器为每个.ts文件生成对应的.d.ts文件。 -
配置 输出目录(可选)。如果希望声明文件输出到特定文件夹,设置
declarationDir选项。{ "compilerOptions": { "declaration": true, "declarationDir": "./dist/types", "emitDeclarationOnly": true } } -
运行 编译命令
tsc。编译器将在指定目录生成声明文件。
7. 发布与引用规范
编写完成的声明文件需要正确配置才能被 TypeScript 识别。
-
修改
package.json文件。添加types或typings字段,指向项目的主声明文件入口。{ "name": "my-awesome-lib", "main": "dist/index.js", "types": "dist/index.d.ts" } -
检查 路径映射。如果使用了路径别名(如
@/utils),需确保tsconfig.json中的paths配置与声明文件结构一致。 -
发布 到 npm。如果是公共库,发布时会自动包含
types字段指向的文件,用户安装后即可自动获得类型提示。
附录:声明关键字对照表
| 关键字 | 适用场景 | 示例 |
|---|---|---|
declare var |
声明全局变量 | declare var VERSION: string; |
declare function |
声明全局函数 | declare function fetch(url: string): void; |
declare class |
声明全局类 | declare class Animal {} |
declare enum |
声明全局枚举 | declare enum Direction { Up, Down } |
declare module |
声明外部模块 | declare module 'http' |
declare global |
在模块中声明全局变量 | declare global { ... } |
export = |
CommonJS 导出 | export = function() {} |
声明文件编写流程图
以下流程图展示了为现有 JavaScript 代码编写声明文件的决策路径:

暂无评论,快来抢沙发吧!