Global space

There is a validator.ts file with the following contents:

const letterRegx = /^[a-zA-Z]+$/;
const numberRegx = / ^ [0-9] + $/;

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

class LettersValidator implements StringValidator {
  isAcceptable(s: string): boolean {
    returnletterRegx.test(s); }}class ZipCodeValidator implements StringValidator {
  isAcceptable(s: string): boolean {
    returnnumberRegx.test(s); }}Copy the code

As you can see, the validator.ts file is neither imported nor exported. Therefore, it is not a custom module. It’s in the global space, it’s in the global space, it’s in the global space. LettersValidator is a class in the global namespace. Can be used directly in any module without reintroducing. There is a main.ts file that reads as follows

export function main() {
  new LettersValidator().isAcceptable('wuhan');
}
main();
Copy the code

No LettersValidator is introduced in main.ts. But you can still use LettersValidator directly. The reason is that LettersValidator is a type defined in global space.

Space module

Suppose you add export to the end of validator.ts.

const letterRegx = /^[a-zA-Z]+$/;
const numberRegx = / ^ [0-9] + $/;

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

class LettersValidator implements StringValidator {
  isAcceptable(s: string): boolean {
    returnletterRegx.test(s); }}class ZipCodeValidator implements StringValidator {
  isAcceptable(s: string): boolean {
    returnnumberRegx.test(s); }}export {
  StringValidator,
  LettersValidator,
  ZipCodeValidator,
}
Copy the code

At this point, validator.ts is a custom module, out of the global namespace. Using LettersValidator without introducing LettersValidator in main.ts causes an error. Validator. ts is a module, and main.ts is a module. To use a type defined in one module in another, it must be imported before it can be used.