标签:
在我们没有引入模块化之前,我们的typescript代码可能这样写:
interface StringValidator { isAcceptable(s: string): boolean; } var lettersRegexp = /^[A-Za-z]+$/; var 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 var strings = [‘Hello‘, ‘98052‘, ‘101‘]; // Validators to use var validators: { [s: string]: StringValidator; } = {}; validators[‘ZIP code‘] = new ZipCodeValidator(); validators[‘Letters only‘] = new LettersOnlyValidator(); // Show whether each string passed each validator strings.forEach(s => { for (var name in validators) { console.log(‘"‘ + s + ‘" ‘ + (validators[name].isAcceptable(s) ? ‘ matches ‘ : ‘ does not match ‘) + name); } });
如果我们加入更多的验证程序,我们就希望有一些合适的结构组织使得我们能够跟踪我们的类型并且不用担心对象的命名冲突。 和用不同的名字放在全局空间不同,我们把对象包装进我们的模块里面。
在这个例子里面,我们把这些相关的验证程序写进一个叫做Validation的模块里面。我们使用关键字export来使得这些接口和类能在外部访问。相反, 变量lettersRegexp 和 numberRegexp 我们放在模块里面使其对外不可见。
module Validation { export interface StringValidator { isAcceptable(s: string): boolean; } var lettersRegexp = /^[A-Za-z]+$/; var 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 var strings = [‘Hello‘, ‘98052‘, ‘101‘]; // Validators to use var validators: { [s: string]: Validation.StringValidator; } = {}; validators[‘ZIP code‘] = new Validation.ZipCodeValidator(); validators[‘Letters only‘] = new Validation.LettersOnlyValidator(); // Show whether each string passed each validator strings.forEach(s => { for (var name in validators) { console.log(‘"‘ + s + ‘" ‘ + (validators[name].isAcceptable(s) ? ‘ matches ‘ : ‘ does not match ‘) + name); } });
标签:
原文地址:http://www.cnblogs.com/ByronWu12345/p/4806890.html