当项目属于大型的时候,有时候会碰到各种文件中污染全局变量名冲突,这没办法避免工作上全局变量名冲突,这样会维护很差的。只有解决办法是Typescript提供了namespace命名空间,这样可以保证局部变量名的内部,与外部各种文件下变量名不会冲突。提供了主要是有:
1.export暴露内部代码;
2.内部模块只能是局部变量名;
3.namespace来声明定义,在外部中,无法直接内部namespace下代码;
4.通过namespace可以帮我们提供逻辑代码抽离。
1.基本命名空间
(1)非export
namespace info{
const _age = 18
function getName(){
return _age
}
}
console.log(_age) //错误,没发现_age变量名
console.log(getName()) // 错误,没发现getName()函数
到时编译转换为js,这样会报错的,因为这个js是没有提供支持namespace命名空间,还有转译后js代码,如下:
var info;
(function (info) {
var _age = 18;
function getName() {
return _age;
}
})(info || (info = {}));
可以发现js本身有立即执行函数,这样函数内部的代码无法从外部来获取的。
为了获取该这个命名空间内部代码或者内部函数,只有通过export关键字把这个命名空间内部代码或者内部函数暴露出来。
namespace info{
const _age = 18
// 使用export
export function getName(){
return _age
}
}
console.log(info.getName()) // 18
可以看到打印出为18,因为通过export关键字才能访问命名空间内部代码或者内部函数。
2.嵌套命名空间
namespace name{
namespace age{
export const b =2
}
}
console.log(name.age.b)
子类命名空间可以被父类命名空间导出,同时可以把子类命名空间的内部变量暴露出来。
3.导入命名空间
index.ts
export namespace info {
export const a = 2
}
index1.ts
import {info} from './index.ts'
console.log(info) // {a:2}
只要通过export关键字,在另一个新文件导入这个命名空间就可以访问到内部的变量。
4.合并命名空间
namespace c{
export const d = 2
}
namespace c{
export const e = 3
}
console.log(c.d) // 2
console.log(c.e) // 3
命名空间可以支持合并的多个命名空间。
5.扩展命名空间
使用reference扩展可以一个命名空间,看下代码:
q.ts文件
/// <reference path="./b.ts"/>
const a: info.fo = info.defa
const b: info.fo = info.get( 'xiaobin', 18 )
console.log( a ) // {name: 'james', age: 30}
console.log( b ) // {name: 'xiaobin', age: 18}
w.ts文件
/// <reference path="./c.ts" />
namespace info {
export const defa: fo = get( 'james', 30);
}
e.ts文件
namespace info {
export interface fo {
name: string;
age: number;
}
export function get( name: string, age: number ): fo {
return { name, age };
}
}
在w.ts文件中,通过reference引入了e.ts文件,扩展info命名空间,内部代码为defa的变量名,而且在w.ts文件中可以访问info中的所有变量get( 'james', 30)。
在q.ts文件中,通过reference引入了w.ts,在q.ts文件中可以访问命名空间info内部的fo、get和defa成员。