天天看點

TypeScript 命名空間

命名空間一個最明确的目的就是解決重名問題。

假設這樣一種情況,當一個班上有兩個名叫小明的學生時,為了明确區分它們,我們在使用名字之外,不得不使用一些額外的資訊,比如他們的姓(王小明,李小明),或者他們父母的名字等等。

命名空間定義了辨別符的可見範圍,一個辨別符可在多個名字空間中定義,它在不同名字空間中的含義是互不相幹的。這樣,在一個新的名字空間中可定義任何辨別符,它們不會與任何已有的辨別符發生沖突,因為已有的定義都處于其他名字空間中。

TypeScript 中命名空間使用 namespace 來定義,文法格式如下:

namespace SomeNameSpaceName {

export interface ISomeInterfaceName { }

export class SomeClassName { }

}

以上定義了一個命名空間 SomeNameSpaceName,如果我們需要在外部可以調用 SomeNameSpaceName 中的類和接口,則需要在類和接口添加 export 關鍵字。

要在另外一個命名空間調用文法格式為:

如果一個命名空間在一個單獨的 TypeScript 檔案中,則應使用三斜杠 /// 引用它,文法格式如下:

以下執行個體示範了命名空間的使用,定義在不同檔案中:

namespace Drawing {

export interface IShape {

draw();

/// <reference path = "IShape.ts" />

export class Circle implements IShape {

public draw() {

console.log("Circle is drawn");

export class Triangle implements IShape {

console.log("Triangle is drawn");

/// <reference path = "Circle.ts" />

/// <reference path = "Triangle.ts" />

function drawAllShapes(shape:Drawing.IShape) {

shape.draw();

drawAllShapes(new Drawing.Circle());

drawAllShapes(new Drawing.Triangle());

使用 tsc 指令編譯以上代碼:

得到以下 JavaScript 代碼:

var Drawing;

(function (Drawing) {

var Circle = /** @class */ (function () {

function Circle() {

Circle.prototype.draw = function () {

};

return Circle;

}());

Drawing.Circle = Circle;

})(Drawing || (Drawing = {}));

var Triangle = /** @class */ (function () {

function Triangle() {

Triangle.prototype.draw = function () {

return Triangle;

Drawing.Triangle = Triangle;

function drawAllShapes(shape) {

使用 node 指令檢視輸出結果為:

命名空間支援嵌套,即你可以将命名空間定義在另外一個命名空間裡頭。

namespace namespace_name1 {

export namespace namespace_name2 {

export class class_name { }

成員的通路使用點号 . 來實作,如下執行個體:

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));

var Runoob;

(function (Runoob) {

var invoiceApp;

(function (invoiceApp) {

var Invoice = /** @class */ (function () {

function Invoice() {

Invoice.prototype.calculateDiscount = function (price) {

return Invoice;

invoiceApp.Invoice = Invoice;

})(invoiceApp = Runoob.invoiceApp || (Runoob.invoiceApp = {}));

})(Runoob || (Runoob = {}));