zoukankan      html  css  js  c++  java
  • 第十章 命名空间

    命名空间

    介绍

    • “内部模块”现在叫做“命名空间”,使用 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 文件也是一一对应的
  • 相关阅读:
    freak out用法
    kinda用法
    比较级与最高级
    issue用法
    invite用法
    yet用法
    follow用法
    get用法
    turn up&turn off&turn on用法
    关于document.lastModified属性
  • 原文地址:https://www.cnblogs.com/zfc2201/p/8166372.html
Copyright © 2011-2022 走看看