[TOC]
命名空间是将许多不同的名称放入全局名称空间,让我们将对象打包到一个命名空间中。
一个验证示例:
namespace Validation {
export interface StringValidator {
isAcceptable(s: string): boolean;
}
const lettersRegexp = /^[A-Za-z]+$/;
const numberRegexp = /^[0-9]+$/;
export class LettersOnlyValidator implements StringValidator {
isAcceptable(s: string) {
return lettersRegexp.test(s);
}
}
export class ZipCodeValidator implements StringValidator {
isAcceptable(s: string) {
return s.length === 5 && numberRegexp.test(s);
}
}
}
// Some samples to try
let strings = ["Hello", "98052", "101"];
// Validators to use
let validators: { [s: string]: Validation.StringValidator } = {};
validators["ZIP code"] = new Validation.ZipCodeValidator();
validators["Letters only"] = new Validation.LettersOnlyValidator();
在本例中,我们将把所有与验证器相关的实体转移到名为Validation的命名空间中。因为我们希望这里的接口和类在命名空间之外可见,所以我们在它们前面加上export。相反,变量lettersRegexp和numberRegexp是实现细节,因此不导出它们,并且对命名空间之外的代码不可见。
多文件命名空间
我们将在多个文件中分割验证命名空间。尽管这些文件是独立的,但它们都可以构成相同的命名空间,并且可以像在一个地方定义的那样使用它们。由于文件之间存在依赖关系,我们将添加引用标记来告诉编译器文件之间的关系。
// Validation.ts
namespace Validation {
export interface StringValidator {
isAcceptable(s: string): boolean;
}
}
// test1.ts
/// <reference path="Validation.ts" />
namespace Validation {
const lettersRegexp = /^[A-Za-z]+$/;
export class LettersOnlyValidator implements StringValidator {
isAcceptable(s: string) {
return lettersRegexp.test(s);
}
}
}
// test2.ts
/// <reference path="Validation.ts" />
namespace Validation {
const numberRegexp = /^[0-9]+$/;
export class ZipCodeValidator implements StringValidator {
isAcceptable(s: string) {
return s.length === 5 && numberRegexp.test(s);
}
}
}
/// <reference path="Validation.ts" />
/// <reference path="test1.ts" />
/// <reference path="test2.ts" />
// Some samples to try
let strings = ["Hello", "98052", "101"];
// Validators to use
let validators: { [s: string]: Validation.StringValidator } = {};
validators["ZIP code"] = new Validation.ZipCodeValidator();
Aliases(别名)
另一种简化命名空间使用的方法是使用import q = x.y.z 为常用对象创建更短的名称。不要与用于加载模块的import x = require(“name”)语法混淆,该语法只是为指定的符号创建一个别名。您可以将这些类型的导入(通常称为别名)用于任何类型的标识符,包括从模块导入创建的对象。
namespace Shapes {
export namespace Polygons {
export class Triangle {}
export class Square {}
}
}
import polygons = Shapes.Polygons;
let sq = new polygons.Square(); // Same as 'new Shapes.Polygons.Square()'
注意,我们没有使用require关键字;相反,我们从要导入的符号的限定名直接赋值。这与使用var类似,但也可以处理导入符号的类型和名称空间含义。重要的是,对于值,import是与原始符号不同的引用,因此对别名var的更改不会反映在原始变量中。
Ambient Namespaces (环境命名空间)
流行库D3在名为D3的全局对象中定义其功能。因为这个库是通过