1. 模块化
- 策略:将代码按照功能拆分成多个模块,每个模块有自己独立的作用域,减少名字空间的全局污染。在 TypeScript 中,ES6 模块是推荐的方式。
- 代码示例:
// user.ts
export interface User {
name: string;
age: number;
}
export function createUser(name: string, age: number): User {
return { name, age };
}
- 在 `main.ts` 中引入使用
// main.ts
import { User, createUser } from './user';
const myUser: User = createUser('John', 30);
console.log(myUser);
2. 命名规范
- 策略:制定严格的命名规范,例如使用前缀或后缀来标识特定功能或模块相关的命名空间。这样即使不同模块有相似功能,通过命名也能区分开。
- 代码示例:
// product - namespace.ts
namespace ProductUtils {
export function calculateTotalPrice(products: { price: number }[]): number {
return products.reduce((total, product) => total + product.price, 0);
}
}
// order - namespace.ts
namespace OrderUtils {
export function calculateOrderTotal(order: { items: { price: number }[] }): number {
return order.items.reduce((total, item) => total + item.price, 0);
}
}
3. 别名(Aliasing)
- 策略:使用别名来简化复杂或可能冲突的名字空间引用,同时也使代码更易读。
- 代码示例:
namespace ComplexNamespace {
export namespace SubNamespace {
export function doSomething(): void {
console.log('Doing something in sub - namespace');
}
}
}
// 使用别名
import SN = ComplexNamespace.SubNamespace;
SN.doSomething();
4. 工具辅助
- 策略:利用 IDE(如 Visual Studio Code)的代码分析和重构功能。IDE 可以帮助检测潜在的命名冲突,并提供重构建议,如重命名等操作。
- 示例:在 Visual Studio Code 中,当检测到命名冲突时,编辑器会有相应的提示,并且可以通过重构功能快速重命名相关的命名空间或标识符。