第7章:模块与命名空间
命名空间(Namespace)的使用场景
1. 什么是命名空间?
命名空间(Namespace)是 TypeScript 提供的一种代码组织方式,用于在全局作用域内划分逻辑分组,避免命名冲突。它类似于其他语言中的“包”或“模块”概念,但具有 TypeScript 特有的实现方式。
namespace MyUtils {
export function log(message: string) {
console.log(message);
}
}
MyUtils.log("Hello from namespace!");
2. 主要使用场景
2.1 避免全局污染
当代码需要在全局作用域中暴露多个相关功能时,命名空间可以将这些功能封装到一个统一的名称下:
namespace Geometry {
export namespace Circle {
export function area(radius: number) {
return Math.PI * radius ** 2;
}
}
}
console.log(Geometry.Circle.area(5)); // 78.54
2.2 兼容旧代码(Legacy JavaScript)
在迁移非模块化的 JavaScript 代码时,命名空间可以逐步重构代码而不破坏原有结构:
// 旧代码
var App = App || {};
App.Models = {};
// TypeScript 改造
namespace App {
export namespace Models {
export class User {}
}
}
2.3 类型声明合并
命名空间可以与其他声明(如类、函数)合并,扩展其功能:
class Validator {
static isEmail() { /*...*/ }
}
namespace Validator {
export static isPhone() { /*...*/ }
}
Validator.isEmail("test@example.com");
Validator.isPhone("123-456-7890");
3. 命名空间的局限性
- 模块化替代:在现代项目中,ES6 模块(
import/export)通常是更好的选择 - 依赖管理:命名空间无法像模块那样明确表达依赖关系
- 打包优化:模块更容易被 Tree Shaking 优化
4. 实际案例
4.1 第三方库的类型扩展
// 扩展 jQuery 类型
namespace JQuery {
interface Static {
toast(message: string): void;
}
}
$.toast("Notification"); // 类型安全调用
4.2 大型应用的分层
namespace EnterpriseApp {
export namespace Services {
export class AuthService {}
}
export namespace Components {
export class Dashboard {}
}
}
5. 最佳实践建议
- 优先使用模块:除非有明确需求(如声明合并或兼容旧系统)
- 避免深层嵌套:超过 2 层的命名空间会增加理解成本
- 配合
/// <reference>:在非模块化环境中管理依赖关系
注意:TypeScript 官方推荐在新项目中使用 ES6 模块,命名空间主要适用于特定场景的遗留代码维护。
