13 · 声明文件、全局声明与模块增强
学完这章,你能给没有类型的 JS 补上
.d.ts,用declare global扩展全局对象,用模块增强补第三方类型,并知道declare为什么一行代码都不会生成。
本章目标
- 能写全局声明、模块声明、
declare global、declare module四种形态 - 能区分「脚本声明」与「模块声明」,并知道
export如何改变文件性质 - 能做模块增强,并避开「相对路径不能用
declare module」等限制 - 能用声明合并扩展接口,同时理解全局污染风险
- 能读懂
TS7016与TS2669
前置知识
- 第 04 章(
interface合并) - 第 07 章(类与模块边界)
- JavaScript 的
<script>与 ESM 区别
从你熟悉的语言出发
| 你熟悉的 | 声明与实现分离 | TypeScript 的对应 | 关键差异 |
|---|---|---|---|
| C/C++ 头文件 | .h 声明 + .c 实现,链接期绑定 |
.d.ts + .js |
.d.ts 只在编译期存在,没有链接产物 |
| Java 接口 | 接口 + 实现类 | interface + declare |
.d.ts 不生成任何字节码或类 |
Go 的 //go:linkname |
手工声明外部符号 | declare |
TS 的 declare 只是承诺,运行时不校验 |
Python .pyi |
类型存根 | .d.ts |
思路接近:类型与实现分离 |
一句话:.d.ts 是「给编译器看的承诺」,不是「给运行时看的代码」。
正文
13.1 .d.ts 里有什么
声明文件只描述形状:
// types/legacy-math.d.ts
interface LegacyMathApi {
readonly version: string;
add(a: number, b: number): number;
}
declare const LegacyMath: LegacyMathApi;三个要点:
- 没有函数体、没有初始化表达式;
declare表示「运行时一定存在」。 - 这个文件没有顶层
export,所以它是脚本声明,LegacyMath是全局名字。 - 编译后不会生成任何
.js。
13.2 脚本声明 vs 模块声明
| 形态 | 判定 | 作用域 | 用法 |
|---|---|---|---|
| 脚本声明 | 没有顶层 import/export |
全局 | 给全局变量、全局接口补类型 |
| 模块声明 | 有顶层 import/export |
文件内 | 声明一个模块的导出 |
一旦在 .d.ts 里写了 export,它就从全局脚本变成模块,全局名字不再可见,必须通过 import 使用。这是新手最常踩的坑。
基线的 moduleDetection: "force" 会把所有 .ts 都当成模块,所以示例里要演示「脚本」时必须显式覆盖为 legacy(见 demo/not-module.ts 的失败配置)。
13.3 全局增强:declare global
export {}; // 让文件成为模块
declare global {
interface Window {
appVersion: string;
}
}declare global 只能在模块内使用,作用是「把模块里的声明放回全局」。常见用途:
- 给
Window加第三方脚本注入的字段。 - 给
Array、String加原型方法(风险高,见反直觉差异)。 - 给
process.env加变量(Node 场景,本教程不展开)。
13.4 模块增强:declare module
import 'analytics';
declare module 'analytics' {
interface Tracker {
trackPage(path: string): void;
}
}两条硬规则:
- 必须先 import 目标模块,否则
declare module会被当成「新建环境模块」,而不是「增强已有模块」。 - 模块名不能是相对路径。
declare module './foo'不生效;增强第三方包用包名,增强本地模块用路径别名或包名。
模块增强只改类型,不改运行时。若第三方库运行时没有 trackPage,调用它照样崩。
13.5 环境模块:declare module '*.css'
资源导入没有类型,可以声明通配模块:
declare module '*.css' {
const css: string;
export default css;
}这让 import css from './a.css' 通过类型检查(运行时由打包器处理)。注意:本教程不安装打包器,所以示例只做类型声明,不实际导入 CSS。
13.6 声明合并
同名 interface 会合并:
interface AppEvents {
ready: void;
}
interface AppEvents {
error: Error;
progress: number;
}
type Keys = keyof AppEvents; // 'ready' | 'error' | 'progress'可合并的声明:interface、namespace、函数重载、enum(与 namespace)。type 别名不能合并,同名直接 TS2300。
13.7 UMD、export = 与 export as namespace
export as namespace MyLib;:给 UMD 包声明一个全局名字,只影响类型,不生成全局变量。export = MyLib;:CommonJS 的导出形态,不能与具名导出混用;消费方用import MyLib = require('my-lib')或默认导入(esModuleInterop恒开)。import x = require('...'):CJS 互操作写法,第 21 章详讲。
TS 7 不再生成 AMD/UMD 产物,但消费以 UMD 形式发布的库仍然需要这些声明。第 22 章会从模块史角度重讲。
13.8 @types 查找与 types 字段
编译器默认按 node_modules/@types/* 找全局声明;tsconfig 的 types: [](基线默认)会关闭自动引入,迫使示例只依赖浏览器 API。库作者则在 package.json 里写:
{
"types": "./dist/types/index.d.ts",
"exports": {
".": {
"types": "./dist/types/index.d.ts",
"import": "./dist/index.js"
}
}
}第 25 章会专门讲声明分发。
类型错误现场
场景一:导入没有声明的 JS。examples/13-declaration-files/01-ambient-declaration/demo/untyped-import.ts:
import { add } from '../lib/legacy-math.js';真实报错(TypeScript 7.0.2):
demo/untyped-import.ts(3,21): error TS7016: Could not find a declaration file for module '../lib/legacy-math.js'. '.../lib/legacy-math.js' implicitly has an 'any' type.TS7016是「找不到声明文件」,不是「文件不存在」。- 修复:写同名
.d.ts、用declare module,或把库改成 TS 源码。
场景二:在非模块里用 declare global。examples/13-declaration-files/02-global-augmentation/demo/not-module.ts(失败配置把 moduleDetection 设为 legacy):
declare global {
interface Window {
broken: string;
}
}真实报错:
demo/not-module.ts(3,9): error TS2669: Augmentations for the global scope can only be directly nested in external modules or ambient module declarations.TS2669表示「全局增强只能放在模块或环境模块里」。- 修复:加一行
export {},文件变成模块即可。
反直觉差异:declare 不会做任何运行时检查
你的直觉:declare const LegacyMath: LegacyMathApi; 就像 C 的 extern,链接器会验证符号存在;运行时应该能保证它真的存在。
实际行为:declare 只是一句承诺,编译器完全不生成代码,也不做运行时校验:
declare const LegacyMath: { add(a: number, b: number): number };
LegacyMath.add(1, 2); // 编译通过;运行时若 LegacyMath 不存在,直接 ReferenceError同理,declare global { interface Window { appVersion: string } } 之后,window.appVersion 的类型是 string,但运行时它可能是 undefined(页面还没写入)。
为什么这样设计:.d.ts 的职责是描述已有的 JavaScript,而不是生成实现。若编译器为每个 declare 插入运行时检查,产物会膨胀、性能下降,也无法在浏览器里「链接」一个不存在的符号。类型声明与实现的一致性由人(或生成工具)保证。
正确写法:
- 给第三方库写声明时,对照源码/文档逐项核对,不要凭印象。
- 全局增强要配运行时初始化(在入口写入默认值),或用可选属性 + 判空。
- 关键边界用运行时校验兜底;类型只负责开发期提示。
示例索引
| 目录 | 演示什么 | 预期看到 |
|---|---|---|
examples/13-declaration-files/01-ambient-declaration/ |
为全局 JS 库写 .d.ts |
3、1.0.0;失败配置贴 TS7016 |
examples/13-declaration-files/02-global-augmentation/ |
declare global 扩展 Window |
1.0.0 两行;失败配置贴 TS2669 |
examples/13-declaration-files/03-module-augmentation/ |
模块增强 Tracker |
无运行时输出;类型测试验证 trackPage |
examples/13-declaration-files/04-declaration-merging/ |
两个文件合并 AppEvents |
无运行时输出;keyof 得到三键 |
练习题
- 给
examples/13-declaration-files/01-ambient-declaration/types/legacy-math.d.ts增加subtract,并在run()里使用;同时让lib/legacy-math.js实现它。 - 给
examples/13-declaration-files/03-module-augmentation增加第二个增强文件,补Tracker.reset(),验证两个增强可以叠加。 - 写一个
declare module '*.svg',默认导出{ src: string },并用类型测试断言默认导出的形状。
-
在
.d.ts里加subtract(a: number, b: number): number;,在 JS 里加同名方法;run()输出api.subtract(5, 2)。类型与实现必须同步,否则运行时报undefined is not a function。 -
新建
types/analytics-augment-2.d.ts,同样import 'analytics'后declare module 'analytics' { interface Tracker { reset(): void } }。两个文件都会合并到同一个接口。 -
declare module '*.svg' { const asset: { src: string }; export default asset; }类型测试可用
typeof import('./logo.svg')['default']断言{ src: string }(需存在一个.svgfixture 或依赖通配声明)。
章末自检
.d.ts会生成运行时代码吗?- 一个
.d.ts有没有export有什么区别? declare global为什么要求文件是模块?- 模块增强为什么必须先
import? export as namespace会创建全局变量吗?TS7016与TS2669分别说明什么?
- 不会。它只参与类型检查。
- 有
export是模块,声明只在该模块内;没有则是全局脚本声明。 - 因为它要把模块内的声明「放回全局」,非模块没有「模块内」这一层。
- 否则
declare module 'x'会被当成新建环境模块,而不是增强已有模块。 - 不会,只影响类型层的全局名字。
TS7016:导入的 JS 没有声明文件;TS2669:declare global出现在了非模块里。
延伸阅读
- TypeScript Handbook:Declaration Files(Introduction、Global、Module Augmentation)
- TypeScript Handbook:Modules 中
export =与import = require - TypeScript Handbook:Declaration Merging
- TypeScript Handbook:tsconfig Reference 中
types、typeRoots条目