「这是我参与2022首次更文挑战的第19天,活动详情查看:2022首次更文挑战」
概述与推荐阅读
简述
命名空间:在代码量较大的情况下,为了避免各种变量命名相冲突,可将相似功能的函数、类、接口 等放置到命名空间内,同java的包、.Net的命名空间一样,TypeScript的命名空间可以将代码包裹起来, 只对外暴露需要在外部访问的对象。命名空间内的对象通过export引出。
命名空间和模块的区别
命名空间:内部模块,主要用于组织代码,避免命名冲突。模块: ts的外部模块的简称,侧重代码的复用,一个模块里可能会有多个命名空间。
推荐阅读
命名空间在一个文件中的基本使用
namespace A{
interface animal{
name:string;
eat():void;
}
export class Fish implements animal {
name: string;
constructor(theName : string) {
this.name = theName;
}
eat(): void {
console.log(`${this.name}在吃小鱼`);
}
}
}
namespace B{
interface animal{
name:string;
eat():void;
}
export class Fish implements animal {
name: string;
constructor(theName : string) {
this.name = theName;
}
eat(): void {
console.log(`${this.name}在吃海藻和虾米`);
}
}
}
let a = new A.Fish('鲨鱼')
a.eat()
let b = new B.Fish('鲶鱼')
b.eat()
这里我们定义了两个命名空间A和B,里面除了eat函数打印内容有一点点细微的区别外,其他变量名、函数名、接口等都是一样的。
这里是可以正常运行打印的,如果我们不用命名空间直接写两个class都是命名为Fish,name会报错标识符重复:
命名空间在多个文件中的基本使用
尽管是不同的文件,它们仍是同一个命名空间,并且在使用的时候就如同它们在一个文件中定义的一样。 因为不同文件之间存在依赖关系,所以我们加入了引用标签来告诉编译器文件之间的关联。 我们的测试代码保持不变。
namespaceModuleOne.ts文件中:
export namespace One{
interface animal{
name:string;
eat():void;
}
export class Fish implements animal {
name: string;
constructor(theName : string) {
this.name = theName;
}
eat(): void {
console.log(`${this.name}吃泥土`);
}
}
}
namespaceModuleTwo.ts文件中:
export namespace Two{
interface animal{
name:string;
eat():void;
}
export class Fish implements animal {
name: string;
constructor(theName : string) {
this.name = theName;
}
eat(): void {
console.log(`${this.name}吃很小的鱼`);
}
}
}
namespace.ts文件中:
import {One} from './namespaceModuleOne'
import {Two} from './namespaceModuleTwo'
let fishOne = new One.Fish('草鱼')
fishOne.eat()
let fishTwo = new Two.Fish('黑鱼')
fishTwo.eat()