- 命名空间
**namespace**
- ts 中命名空间使用
**namespace**
来定义 - ts 命名空间用于解决重名问题
- 假设这样一种情况,当一个班上有两个名叫小明的学生时,为了明确区分它们,我们在使用名字之外,不得不使用一些额外的信息,比如他们的姓(王小明,李小明),或者他们父母的名字等等
- 命名空间定义了标识符的可见范围,一个标识符可在多个名字空间中定义,它在不同名字空间中的含义是互不相干的
- 在一个新的名字空间中可定义任何标识符,它们不会与任何已有的标识符发生冲突,因为已有的定义都处于其他名字空间中
- 如果一个命名空间在一个单独的 ts 文件中,则应使用三斜杠
**///**
引用它 - 命名空间支持嵌套,即你可以将命名空间定义在另外一个命名空间里头
// IShape.ts
namespace Drawing {
export interface IShape {
draw();
}
}
// Circle.ts
/// <reference path = "IShape.ts" />
namespace Drawing {
export class Circle implements IShape {
public draw() {
console.log("Circle is drawn");
}
}
}
// Triangle.ts
/// <reference path = "IShape.ts" />
namespace Drawing {
export class Triangle implements IShape {
public draw() {
console.log("Triangle is drawn");
}
}
}
// TestShape.ts
/// <reference path = "IShape.ts" />
/// <reference path = "Circle.ts" />
/// <reference path = "Triangle.ts" />
function drawAllShapes(shape: Drawing.IShape) {
shape.draw();
}
drawAllShapes(new Drawing.Circle());
drawAllShapes(new Drawing.Triangle());
// Circle is drawn
// Triangle is drawn
输入 tsc --out app.js TestShape.ts
编译生成结果 app.js
,然后再使用 node 命令 node .\app.js
来执行编译结果。
编译后得到的 app.js 文件内容如下:
// Circle.ts
/// <reference path = "IShape.ts" />
var Drawing;
(function (Drawing) {
var Circle = /** @class */ (function () {
function Circle() {
}
Circle.prototype.draw = function () {
console.log("Circle is drawn");
};
return Circle;
}());
Drawing.Circle = Circle;
})(Drawing || (Drawing = {}));
// Triangle.ts
/// <reference path = "IShape.ts" />
var Drawing;
(function (Drawing) {
var Triangle = /** @class */ (function () {
function Triangle() {
}
Triangle.prototype.draw = function () {
console.log("Triangle is drawn");
};
return Triangle;
}());
Drawing.Triangle = Triangle;
})(Drawing || (Drawing = {}));
// TestShape.ts
/// <reference path = "IShape.ts" />
/// <reference path = "Circle.ts" />
/// <reference path = "Triangle.ts" />
function drawAllShapes(shape) {
shape.draw();
}
drawAllShapes(new Drawing.Circle());
drawAllShapes(new Drawing.Triangle());
// Circle is drawn
// Triangle is drawn
// Invoice.ts
namespace Runoob {
export namespace invoiceApp {
export class Invoice {
public calculateDiscount(price: number) {
return price * .40;
}
}
}
}
/// <reference path = "Invoice.ts" />
var invoice = new Runoob.invoiceApp.Invoice();
console.log(invoice.calculateDiscount(500));
// 200