元素码农
基础
UML建模
数据结构
算法
设计模式
网络
TCP/IP协议
HTTPS安全机制
WebSocket实时通信
数据库
sqlite
postgresql
clickhouse
后端
rust
go
java
php
mysql
redis
mongodb
etcd
nats
zincsearch
前端
浏览器
javascript
typescript
vue3
react
游戏
unity
unreal
C++
C#
Lua
App
android
ios
flutter
react-native
安全
Web安全
测试
软件测试
自动化测试 - Playwright
人工智能
Python
langChain
langGraph
运维
linux
docker
工具
git
svn
🌞
🌙
目录
▶
TypeScript环境准备
安装与配置
第一个TS程序
编译流程解析
▶
基础类型系统
类型注解语法
原始类型定义
数组与元组
接口与对象
▶
高级类型系统
泛型编程
条件类型
映射类型
类型推断
类型保护
高级类型工具
▶
函数开发
函数类型声明
可选参数与默认值
箭头函数应用
函数重载
泛型函数
▶
类与面向对象
类的定义
继承与修饰符
存取器使用
抽象类与接口
泛型类与抽象类
访问修饰符与属性
▶
模块化开发
模块导入导出
类型声明文件
命名空间
模块解析策略
▶
工程实践
tsconfig详解
常见编译选项
项目构建配置
代码组织最佳实践
单元测试
调试技巧
▶
常见问题
类型错误处理
类型断言技巧
类型兼容性
版本迁移指南
发布时间:
2025-03-31 09:29
↑
☰
# 命名空间 命名空间(Namespace)是TypeScript提供的一种组织代码的方式,它可以帮助我们避免命名冲突并更好地组织代码结构。本文将详细介绍命名空间的使用方法。 ## 基本语法 ### 定义命名空间 ```typescript // validation.ts namespace Validation { // 导出接口 export interface StringValidator { isValid(s: string): boolean; } // 导出类 export class LettersOnlyValidator implements StringValidator { isValid(s: string): boolean { return /^[A-Za-z]+$/.test(s); } } // 导出常量 export const numberRegexp = /^[0-9]+$/; // 内部(非导出)函数 function checkLength(s: string): boolean { return s.length > 0; } } ``` ### 使用命名空间 ```typescript // app.ts /// <reference path="validation.ts" /> let validators: { [s: string]: Validation.StringValidator } = {}; validators["letters"] = new Validation.LettersOnlyValidator(); // 使用命名空间中的类型 let lettersValidator: Validation.StringValidator = new Validation.LettersOnlyValidator(); ``` ## 嵌套命名空间 ```typescript namespace Shapes { export namespace Polygons { export class Triangle { constructor(public sideLength: number) {} } export class Square { constructor(public sideLength: number) {} } } } // 使用嵌套命名空间 let triangle = new Shapes.Polygons.Triangle(10); let square = new Shapes.Polygons.Square(10); ``` ## 别名 ```typescript // 创建命名空间别名 import polygons = Shapes.Polygons; let triangle = new polygons.Triangle(10); // 为深层嵌套创建别名 namespace Shapes { export namespace Polygons { export namespace Triangles { export class Equilateral { constructor(public sideLength: number) {} } } } } import EquilateralTriangle = Shapes.Polygons.Triangles.Equilateral; let triangle = new EquilateralTriangle(10); ``` ## 分离到多个文件 ### 文件1: point.ts ```typescript namespace Geometry { export interface Point { x: number; y: number; } export class PointUtils { static distance(p1: Point, p2: Point): number { let dx = p1.x - p2.x; let dy = p1.y - p2.y; return Math.sqrt(dx * dx + dy * dy); } } } ``` ### 文件2: circle.ts ```typescript /// <reference path="point.ts" /> namespace Geometry { export class Circle { constructor( public center: Point, public radius: number ) {} area(): number { return Math.PI * this.radius * this.radius; } } } ``` ## 命名空间与模块的结合 ```typescript // myModule.ts export namespace MyNamespace { export interface MyInterface { value: string; } export class MyClass implements MyInterface { constructor(public value: string) {} } } // 使用导出的命名空间 import { MyNamespace } from './myModule'; let instance = new MyNamespace.MyClass("Hello"); ``` ## 最佳实践 1. **组织相关功能**: ```typescript namespace Utilities { export namespace Math { export function add(x: number, y: number): number { return x + y; } } export namespace String { export function reverse(s: string): string { return s.split("").reverse().join(""); } } } ``` 2. **避免命名冲突**: ```typescript namespace App { export namespace Models { export class User {} } export namespace ViewModels { export class User {} } } // 使用时明确指定命名空间 let model = new App.Models.User(); let viewModel = new App.ViewModels.User(); ``` 3. **合理使用导出**: ```typescript namespace Configuration { // 内部实现 function validateConfig(config: any): boolean { // 实现验证逻辑 return true; } // 公共API export function loadConfig(path: string): any { let config = {}; if (validateConfig(config)) { return config; } throw new Error("Invalid configuration"); } } ``` ## 常见问题 1. **命名空间vs模块**: ```typescript // 推荐使用模块(ES6模块) export interface MyInterface {} export class MyClass {} // 而不是命名空间 namespace MyNamespace { export interface MyInterface {} export class MyClass {} } ``` 2. **命名空间合并**: ```typescript namespace Animals { export class Cat {} } namespace Animals { export class Dog {} } // 两个命名空间会合并 let cat = new Animals.Cat(); let dog = new Animals.Dog(); ``` ## 下一步 掌握了命名空间后,你可以: 1. 学习模块打包工具的使用 2. 探索项目结构组织方式 3. 实践大型应用程序开发 4. 了解更多TypeScript高级特性 通过合理使用命名空间,你可以更好地组织和管理TypeScript代码。但在现代TypeScript开发中,建议优先使用ES6模块系统。