跳到主要内容

namespace 命名空间

定义命名空间

定义命名空间
namespace SomeNameSpaceName {
export interface ISomeInterfaceName {}
export class SomeClassName {}
}

命名空间调用

命名空间调用语法格式为:
SomeNameSpaceName.SomeClassName

命名空间文件引用 ///

如果一个命名空间在一个单独的 TypeScript 文件中,则应使用三斜杠 /// 引用它,语法格式如下:
/// <reference path = "SomeFileName.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())

嵌套命名空间

命名空间支持嵌套,即你可以将命名空间定义在另外一个命名空间里头。
namespace namespace_name1 {
export namespace namespace_name2 {
export class class_name {}
}
}
  • 成员的访问使用点号 . 来实现,如下实例:
Invoice.ts 文件代码:
namespace Runoob {
export namespace invoiceApp {
export class Invoice {
public calculateDiscount(price: number) {
return price * 0.4
}
}
}
}
InvoiceTest.ts 文件代码:
/// <reference path = "Invoice.ts" />
var invoice = new Runoob.invoiceApp.Invoice()
console.log(invoice.calculateDiscount(500))