TypeScript Namespace Cleaning

1. Introduction

1. Namespaces are primarily used to organize code so that you can record their types while also worrying about naming conflicts with other objects.

2. Namespaces can be separated into multiple files as C#

2. Single file

namespace Valid1 {
    export interface StringValidator {
        isAcceptable(s: string): boolean;
    }
    const lettersRegexp = /^[A-Za-z]+$/;
    const numberRegex = /^[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 && numberRegex.test(s);
        }
    }
}

//Use content under namespace
let strings =['Hello','98052','101'];
let validators:{[s:string]:Valid1.StringValidator;}={};
validators['Zip code']=new Valid1.ZipCodeValidator();
validators['Letters only']=new Valid1.LettersOnlyValidator();

//Traverse strings, traverse validators
for(let s of strings){
    for(let name in validators){
        console.log(`${s}--${validators[name].isAcceptable(s)?"matches":"does not match"}>${name}`);
    }
}

3. Multiple Documents

1. Interface file IString.ts

namespace Valid2{
    export interface StringValidator{
        isAcceptable(s:string):boolean;
    }
}
2.LettersOnlyValidator.ts file

/// <refrences path="IString.ts" />
namespace Valid2{
    const lettersRegexp=/^[A-Za-z]+$/;
    export class LettersOnlyValidator implements StringValidator{
        isAcceptable(s:string){
            return lettersRegexp.test(s);
        }
    }
}
3.ZipCodeValidator.ts file

/// <refrences path="IString.ts" />
namespace Valid2 {
    const numberRegexp = /^[0-9]+$/;
    export class ZipCodeValidator implements StringValidator {
        isAcceptable(s: string) {
            return s.length === 5 && numberRegexp.test(s);
        }
    }
}
4. Test files

/// <refrences path="IString.ts" />
/// <refrences path="LetersOnlyValidator.ts" />
/// <refrences path="ZipCodeValidator.ts" />
namespace test3 {
    let strings = ['Hello', '98052', '101'];
    let validators: { [s: string]: Valid2.StringValidator; } = {};
    validators['ZipCode'] = new Valid2.ZipCodeValidator();
    validators['LettersOnly'] = new Valid2.LettersOnlyValidator();

    for (let s of strings) {
        for (let name in validators) {
            console.log(`${s}--${validators[name].isAcceptable(s) ? "matches" : "does not match"}---->${name}`);
        }
    }
}

5. Test Page

<script src="out/IString.js"></script>
<script src="out/LettersOnlyValidator.js"></script>
<script src="out/ZipCodeValidator.js"></script>
<script src="out/test3.js"></script>

Explain:

1. Reference other file namespaces using: /// <reference path="Validation.ts"/>
2. Namespace file generation, the first kind, separate file generation, when used, refer to in order, as in this example; the second kind, can merge the same namespace into one file generation

4. Use aliases

Aliases simplify the use of namespaces.

Syntax: import q = x.y.z

namespace Shapes {
    export namespace Polygons {
        export class Triangle { }
        export class Square { }
    }
}

import polygons = Shapes.Polygons;
let sq = new polygons.Square(); // Same as "new Shapes.Polygons.Square()"
Note that instead of using the require keyword, we use the qualified name assignment of the imported symbol directly. This is similar to using var, but it also applies to types and imported symbols with namespace meaning. Importantly, for values, import generates references that are different from the original symbol, so changing the var value of the alias does not affect the value of the original variable.

5. Namespaces versus modules

1. Namespace use

A common JavaScript object with a name whose namespace is under the global namespace.This makes the namespace very easy to use.

But like his global namespace pollution, it is difficult to identify dependencies between components, especially in large projects.

2. Using modules

Like namespaces, modules can contain declarations of code.The difference is that a module can declare its dependencies.

Modules add dependencies to the module loader (for example, CommonJS/Require.js).Modules also provide better code reuse, greater closeness, and better tool optimization.

For NodeJs applications, modules are the default and recommended way to block code.

A js file corresponds to a module.

3. Import import should be used for module references.

Use /// <reference> to reference module files for namespaces or external modules

4. Namespaces should not be used for modules, in order to provide logical grouping and avoid naming conflicts.The module file itself is already a logical grouping, and its name is specified by the code that imports the module, so there is no need to add an additional module layer to the exported object.


More:

TypeScript module collation (3) using other JavaScript Libraries

TypeScript module collation (2) compilation generation

TypeScript Development Environment for NodeJs--VS Code

Keywords: TypeScript Javascript

Added by TheJoey on Sun, 16 Jun 2019 19:05:40 +0300