typescript-命名空间

376 阅读2分钟

命名空间,之前叫做内部模块。

命名空间一个最明确的目的就是解决重名问题

第一步

定义一个 add 函数

function add(x: number, y: number): number {
  return x + y;
}

假如说我们此时还需要一个相加的函数,功能是这样的

function add(x: number, y: number): number {
  return x * 2 + y * 2;
}

如果想同时存在的话,我们可以使用不同的函数命名。

但是使用命名空间,同样可以解决这个问题。

命名空间

我们可以将函数包裹到不同命名空间内,而不是全局命名空间下

使用命名空间

namespace A {
  function add(x: number, y: number): number {
    return x + y;
  }
}

namespace B {
  function add(x: number, y: number): number {
    return x * 2 + y * 2;
  }
}

但是此时外部是访问不到这些方法的。

如果我们想让函数在命名空间之外也是可访问的,需要使用 export。如果存在一些内部的数据,可以不暴露给外部。

namespace A {
  export function add(x: number, y: number): number {
    return x + y;
  }
}

namespace B {
  function add(x: number, y: number): number {
    return x * 2 + y * 2;
  }
}

console.log(A.add(2, 4));

分离到多文件

当应用变得越来越大时,我们需要将代码分离到不同的文件中以便于维护。

分别拆分成不同的文件,尽管文件不同,但是它们还是属于同一个命名空间

因为不同文件之间存在依赖关系,所以我们加入了引用标签来告诉编译器文件之间的关联。

Validation.ts

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

LettersOnlyValidator.ts

/// <reference path="Validation.ts" />

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

tests.ts

/// <reference path="Validation.ts" />
/// <reference path="LettersOnlyValidator.ts" />

// use

new Validator.LettersOnlyValidator().isAcceptable("abc"); // true

别名

另一种简化命名空间操作的方法是使用import q = x.y.z给常用的对象起一个短的名字。

// use
import l = Validator.LettersOnlyValidator;

new l().isAcceptable("abc"); // true