命名空间
命名空间:
在代码量较大的情况下,为了避免各种变量名相冲突,可以将相似功能的函数、类、接口等放置到命名空间内。同Java的包、.net的命名空间一样,TypeScript的命名空间可以将代码包裹起来,只对外暴露需要在外部访问的对象。
命名空间和模块的区别:
- 命名空间:内部模块,主要用于组织代码,避免命名冲突
- 模块:ts的外部模块的简称,侧重代码的复用,一个模块里可能会有多个命名空间。
namespace A {
interface Animal {
name: string;
eat(food: string): void;
}
export class Dog implements Animal {
name: string;
constructor(n: string) {
this.name = n;
}
eat(food: string) {
console.log(`${this.name}吃${food}`);
}
}
class Cat implements Animal {
name: string;
constructor(n: string) {
this.name = n;
}
eat(food: string): void {
console.log(`${this.name}吃${food}`);
}
}
}
namespace B {
interface Animal {
name: string;
eat(food: string): void;
}
export class Dog implements Animal {
name: string;
constructor(n: string) {
this.name = n;
}
eat(food: string) {
console.log(`${this.name}吃吃吃吃${food}`);
}
}
}
let d = new A.Dog('小黑');
d.eat('狗粮');
let d1 = new B.Dog('狗狗');
d1.eat('狗粮');
在外部其他模块使用
import {A } from './modules/a'
let d=new A.Dog('小黑');
d.eat('狗粮');