模块增强(Module Augmentation)
一句话解释
模块增强使用 declare module 向现有模块添加类型/方法。
用大白话说
模块增强让你在不修改原始源码的情况下扩展现有模块的类型声明。使用 declare module "module-name" 添加新导出或修改现有类型。常见用例:1. 扩展库类型——向第三方类添加方法
- 插件模式——为添加功能的插件声明类型
- 声明合并——合并接口声明
TypeScript 将增强声明与原始声明合并。这是仅类型的——无运行时效果。适用于扩展 Express 请求、Jest 匹配器、Redux 状态等。
示例
typescript
// Augment Express Request to include a custom property
declare module "express-serve-static-core" {
interface Request {
user?: { id: string; name: string };
}
}
// Now req.user is typed everywhere
import express from "express";
const app = express();
app.use((req, res, next) => {
req.user = { id: "1", name: "Alice" }; // Typed!
next();
});
// Augment Array prototype (for demonstration)
declare global {
interface Array<T> {
last(): T | undefined;
}
}declare module 将新类型合并到现有模块。Express 的 Request 现在有类型化的 user 属性,无需修改库。
常见混淆
容易混淆的对象: 环境模块
关键区别: 环境模块(declare module 'foo')描述运行时存在但无 TypeScript 类型的模块。模块增强(declare module 'foo' { ... })向已有类型的模块添加内容。环境从头创建;增强扩展现有。
相关术语
相关资源
相关课程
- TypeScript 模块
模块增强。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。