TypeScript 学习笔记:属性索引器

export interface StringValidator {
    isAcceptable(s: string): boolean;
}

const lettersRegexp = /^[A-Za-z]+$/;
export class LettersOnlyValidator implements StringValidator {
    isAcceptable(s: string) {
        return lettersRegexp.test(s);
    }
}

const numberRegexp = /^[0-9]+$/;
export class ZipCodeValidator implements StringValidator {
    isAcceptable(s: string) {
        return s.length === 5 && numberRegexp.test(s);
    }
}

// 开始测试
let strings = ["Hello", "98052", "101"];

// Validators to use
let validators: { [key: string]: StringValidator; } = {};
validators["邮政编码"] = new ZipCodeValidator();
validators["纯字符"] = new LettersOnlyValidator();

// Show whether each string passed each validator
strings.forEach(stringItem => {
    for (let valName in validators) { 
        console.log(`"${stringItem}" - ${validators[valName].isAcceptable(stringItem) ? "匹配" : "不匹配"} ${valName}`);
    }
});


运行结果如下:

"Hello" - 不匹配 邮政编码
"Hello" - 匹配 纯字符
"98052" - 匹配 邮政编码
"98052" - 不匹配 纯字符
"101" - 不匹配 邮政编码
"101" - 不匹配 纯字符

我是真搞不懂这一句,太奇妙.... 

  1. let validators: { [key: string]: StringValidator; } = {};  


你可能感兴趣的:(TypeScript)