接 上篇 。
在项目根目录中新建一个./module的文件夹,在里面创建如下ts文件。
文件:Validation.ts
1 // 例,Validation.ts文件作为一个模块(module) 2 // 使用export关键字将接口“StringValidator”暴露给外界 3 4 export interface StringValidator { 5 isAcceptable(s: string): boolean ; 6 }
文件名:ZipCodeValidator.ts
1 / * 2 * ///<reference path="./Validation.ts" /> 这种引入模块的写法是老版本的,不建议继续使用 3 * */ 4 5 // 使用import关键字将Validation文件中的StringValidator引入 6 import {StringValidator} from "./Validation"; // 导入文件中的StringValidator接口 7 8 const numberRegexp = /^[0-9]+$/ ; 9 10 export class ZipCodeValidator implements StringValidator { 11 isAcceptable(s: string) { 12 return s.length === 6 && numberRegexp.test(s); 13 } 14 }
文件名:TelValidator.ts
1 // 还有一种引入的写法如下,把这个文件用以“validator”作为命名空间导入 2 import validator = require('./Validation' ); 3 4 let telReg = /^(13[0-9]|15[0-9]|18[0-9])\d{8}$/ ; 5 6 export class TelValidator implements validator.StringValidator { 7 isAcceptable(s: string) { 8 return telReg.test(s); 9 } 10 }
文件:ParseIntBasedZipCodeValidator.ts
1 // 也可以使用这种写法,类似python的引入写法,并给这个模块起别名 2 import * as validator from "./Validation" ; 3 4 // 使用别名就可以“点”出来模块中export暴露出来的内容 5 export class ParseIntBasedZipCodeValidator implements validator.StringValidator{ 6 isAcceptable(s: string) { 7 return s.length === 5 && parseInt(s).toString() === s; 8 } 9 } 10 11 // 导出原先的验证器但做了重命名 12 export {StringValidator as ValidatorBase} from "./Validation";
命名空间
文件名:University.ts
1 /* *
2 * 命名空间,关键字“namespace”
3 * 很多编程语言中都有这个概念,大家都是类似的作用
4 */
5
6 export namespace Earth {
7
8 export class Person {
9 planet: string = "地球" ;
10 constructor(readonly name: string, readonly age: number) {
11 }
12
13 SayHi(): void {
14 console.log(`我是${ this .name},我来自${ this .planet}`)
15 }
16 }
17 }
18
19 export namespace Mars {
20
21 export class Person {
22 planet: string = "火星" ;
23 constructor(readonly name: string, readonly age: number) {
24 }
25
26 SayHi(): void {
27 console.log(`我是${ this .name},我来自${ this .planet}`)
28 }
29 }
30 }
1 import * as university from "./University"
2
3 // 使用命名空间区分同名类
4 let earther = new university.Earth.Person("小明", 28 );
5 let marser = new university.Mars.Person("哈努纳汉", 342 );
6
7 earther.SayHi(); // 我是小明,我来自地球
8 marser.SayHi(); // 我是哈努纳汉,我来自火星
9
10 // 注意一点,这段代码在浏览器中运行会报错,是因为不支持“export”这个用法,但是在控制台使用nodejs执行是可以正常调用的,如果想在浏览器中运行可以使用webpack
查看更多关于TypeScript入门笔记(四)的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://www.haodehen.cn/did223447