命名空间:内部模块,主要用于组织代码,避免命名冲突。
关键字:namespace
//俩个类命名冲突 class Dog{ name: string; constructor(name: string) { this.name = name; } eat() { console.log(`${this.name} 在吃骨头。`); } } class Dog{ name: string; constructor(name: string) { this.name = name; } eat() { console.log(`${this.name} 在吃骨头。`); } }
//命名空间 namespace 后加自定义 模块名称。 namespace A{ //如果外部访问此类需要export 导出 export class Dog{ name: string; constructor(name: string) { this.name = name; } eat() { console.log(`${this.name} 在吃骨头。`); } } } var a = new A.Dog('小黑') a.eat(); namespace B{ //如果外部访问此类需要export 导出 export class Dog{ name: string; constructor(name: string) { this.name = name; } eat() { console.log(`${this.name} 在吃骨头。`); } } } var b = new B.Dog('大黄') b.eat(); //如果模块化开发 需要暴露A和B,则在namespace前加export export namespace A{} export namespace B{}