• 第十章 命名空间


    命名空间

    介绍

    • “内部模块”现在叫做“命名空间”,使用 namespace 关键字声明
    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();
    
    // Show whether each string passed each validator
    for (let s of strings) {
        for (let name in validators) {
            console.log(
                `"${s}" - ${
                    validators[name].isAcceptable(s) ? "matches" : "does not match"
                } ${name}`
            );
        }
    }
    
    • 相同命名空间可以在多个文件中使用

    模块

    • 对模块使用///
    // In a .d.ts file or .ts file that is not a module:
    declare module "SomeModule" {
        export function fn(): string;
    }
    
    /// <reference path="myModules.d.ts" />
    import * as m from "SomeModule";
    
    • 就像每个 JS 文件对应一个模块一样,TypeScript 里模块文件与生成的 JS 文件也是一一对应的
  • 相关阅读:
    hdu 1203 I NEED A OFFER (0-1背包)
    hdu 2191 悼念512汶川大地震遇难同胞——珍惜现在,感恩生活
    hdu 1284 钱币兑换问题 完全背包
    hdu 1114 Piggy-Bank 完全背包
    hdu 2955 Robberies 0-1背包/概率初始化
    hdu 2602 Bone Collector 背包入门题
    hdu 1002 A+B problem II
    hdu 2689 Sort it
    hdu 1874 畅通工程续 Dijkstra
    hdu 1232 畅通工程 并查集
  • 原文地址:https://www.cnblogs.com/zfc2201/p/8166372.html
Copyright © 2020-2023  润新知