# 命名空间
**关于术语的说明:**需要注意的是,在 TypeScript 1.5 中,命名法发生了变化。"Internal modules" 现在是 "namespaces"。"External modules" 现在只是 "modules",以符合
ECMAScript 2015
的术语,(即module X {
等同于现在首选的namespace X {
)。
这篇文章概述了在 TypeScript 中使用命名空间(以前是 "internal modules")来组织代码的各种方法。正如我们在关于术语的注释中提到的那样,"internal modules" 现在称为 "namespaces"。此外,在声明内部模块时使用 module
关键字的任何地方,都可以并且应该使用 namespace
关键字。这通过使用类似名称的术语使新用户重载来避免混淆新用户。
# 第一步
让我们从将在整个页面中用作示例的程序开始。我们编写了一组简单的字符串验证器,您可能会编写这些验证器来检查用户在网页表单上的输入或检查外部提供的数据文件的格式。
# 单个文件中的验证器
interface StringValidator {
isAcceptable(s: string): boolean;
}
let lettersRegexp = /^[A-Za-z]+$/;
let numberRegexp = /^[0-9]+$/;
class LettersOnlyValidator implements StringValidator {
isAcceptable(s: string) {
return lettersRegexp.test(s);
}
}
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]: StringValidator } = {};
validators["ZIP code"] = new ZipCodeValidator();
validators["Letters only"] = new LettersOnlyValidator();
// Show whether each string passed each validator
for (let s of strings) {
for (let name in validators) {
let isMatch = validators[name].isAcceptable(s);
console.log(`'${s}' ${isMatch ? "matches" : "does not match"} '${name}'.`);
}
}
+ 
关注公众号,获取验证码 !
验证码: