命名空间
在js中命名空间能有有效的避免全局污染
- 在src目录下新建 a.ts b.ts
- //命名空间和模块不要混用,不要再模块中使用命名空间
- //命名空间最好在全局环境中使用
namespace Shape {
const pi = Math.PI
export function cricle(r: number) {
return pi * r ** 2
}
}
//三斜线引用
/// <reference path="a.ts" />
namespace Shape {
export function square(x: number) {
return x * x
}
}
Shape.cricle(1);
Shape.square(1);
-
先编译 a.ts b.ts
tsc ./src/b.ts
-
在index.html中引入
<script src="src/a.js"></script>
<script src="src/b.js"></script>
-
修改 b.ts
/// <reference path="a.ts" /> namespace Shape { export function square(x: number) { return x * x } } console.log(Shape.cricle(1)) console.log(Shape.square(1)) //命名空间和模块不要混用,不要再模块中使用命名空间 //命名空间最好在全局环境中使用
-
重新编译
名称空间别名问题
//import不是导入的意思~
import cricle = Shape.cricle
console.log(cricle(2))
声明合并
编译器会把程序中多个地方具有相同名称的声明合并为一个声明
可以把程序中散落各处的重名声明合并在一起
接口&函数 的声明合并
-
在src下新建 merge.ts
//接口&函数 的声明合并 interface AA { x: number; // y: string; foo(bar: number): number; //5 foo(bar: '1'): number; //2 } interface AA { y: number foo(bar: string): string; //3 foo(bar: number[]): number[]; //4 foo(bar: '2'): number; //1 } let a1: AA = { x: 1, y: 1, foo(bar: any) { return bar } }
命名空间与函数 的声明合并
在命名空间中导出的成员不可以重复定义
//src/a.ts
namespace Shape {
const pi = Math.PI
export function cricle(r: number) {
return pi * r ** 2
}
// export function square(x: number) {
// return x * x
// }
}
-
在 merge.ts 中追加
//命名空间和函数的 声明合并 function Lib() { } namespace Lib { export let version = '1.0' } console.log(Lib.version) //1.0 //node:命名空间要放在后面
命名空间与类 的声明合并
-
在 merge.ts 中追加
// 命名空间与类 的声明合并 class C2 { } namespace C2 { export let state = 1 } console.log(C2.state) //node:命名空间要放在后面
命名空间与枚举 的声明合并
-
在 merge.ts 中追加
//命名空间与枚举 的声明合并 enum Color { Red1, Yellow1, Bule1 } namespace Color { export function mix() { } } console.log(Color) //node:命名空间与枚举顺序无要求