介绍

  • “内部模块”现在叫做“命名空间”,使用 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 文件也是一一对应的

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-11-16
  • 2021-06-10
  • 2021-09-01
  • 2022-12-23
  • 2021-05-31
猜你喜欢
  • 2021-11-05
  • 2022-01-23
  • 2022-02-27
  • 2021-08-28
  • 2022-12-23
  • 2021-09-27
  • 2022-01-25
相关资源
相似解决方案