主题
TypeScript 命名空间详解
更新: 9/4/2025字数: 0 字 时长: 0 分钟
命名空间(Namespace)是 TypeScript 早期提供的代码组织方式,用于在全局作用域内创建隔离的代码区域,避免命名冲突。
虽然现代 TypeScript 项目更多使用模块(ES6 Modules),但理解命名空间仍然很重要,特别是在维护旧代码或某些特殊场景时。
一、基本概念
1. 定义命名空间
使用 namespace 关键字定义:
typescript
namespace MyNamespace {
export interface Person {
name: string;
age: number;
}
export function greet(person: Person) {
return `Hello, ${person.name}`;
}
}2. 使用命名空间内容
通过完全限定名访问:
typescript
const user: MyNamespace.Person = { name: "Alice", age: 25 };
console.log(MyNamespace.greet(user));二、命名空间特性
1. 嵌套命名空间
支持多级嵌套结构:
typescript
namespace Outer {
export namespace Inner {
export const message = "Hello from inner";
}
}
console.log(Outer.Inner.message);2. 拆分命名空间
同一个命名空间可以分布在多个文件中:
file1.ts
typescript
namespace MyLib {
export function func1() {
/*...*/
}
}file2.ts
typescript
namespace MyLib {
export function func2() {
/*...*/
}
}3. 别名
使用 import 创建别名简化访问:
typescript
import NS = MyNamespace;
const user: NS.Person = { name: "Bob", age: 30 };三、命名空间最佳实践
1. 与模块结合使用
typescript
// shapes.ts
export namespace Shapes {
export class Circle {
/*...*/
}
export class Square {
/*...*/
}
}
// 使用时
import { Shapes } from "./shapes";
let circle = new Shapes.Circle();2. 避免过度嵌套
建议不超过 2-3 层嵌套:
typescript
// 不推荐
namespace A.B.C.D.E {
export class DeepClass {}
}
// 推荐
namespace App {
export namespace Models {
export class User {}
}
}3. 使用合并增强
typescript
// 扩展已有命名空间
namespace MyLib {
export function newFunction() {
/*...*/
}
}