主题
namespace
什么是 namespace
namespace 是 TypeScript 早期提供的一种组织代码方式,用来把一组相关类型、变量和函数包裹在同一个命名空间中,避免全局作用域命名冲突。
ts
namespace Geometry {
export interface Point {
x: number
y: number
}
export function distance(a: Point, b: Point) {
const dx = a.x - b.x
const dy = a.y - b.y
return Math.sqrt(dx * dx + dy * dy)
}
}
const p1: Geometry.Point = { x: 0, y: 0 }
const p2: Geometry.Point = { x: 3, y: 4 }
console.log(Geometry.distance(p1, p2))export 的作用
在 namespace 内部声明的成员,只有通过 export 导出后,外部才能访问。
ts
namespace UserStore {
const cache = new Map<string, string>()
export function set(id: string, name: string) {
cache.set(id, name)
}
}
UserStore.set('1', 'Tom')上面的 cache 没有导出,因此只能在 UserStore 内部使用。
什么时候会看到 namespace
- 维护老项目或历史 TypeScript 代码
- 编写全局库的声明文件
- 阅读某些
.d.ts类型定义时
例如在声明文件中,经常会看到这种写法:
ts
declare namespace MyLibrary {
function create(name: string): void
}namespace 和 ES Module 的区别
namespace 方式
- 是 TypeScript 提供的组织方式
- 更常见于旧代码或声明文件
- 通过命名空间对象访问成员
ES Module 方式
- 是 JavaScript 标准模块系统
- 使用
import/export - 更适合现代工程化项目
ts
// math.ts
export function sum(a: number, b: number) {
return a + b
}
// app.ts
import { sum } from './math'
console.log(sum(1, 2))当前建议
在现代项目中,优先使用 ES Module 管理代码组织。
namespace 更适合以下场景:
- 兼容旧项目
- 阅读历史代码
- 编写或理解全局声明文件
