“This is the third day of my participation in the August More Text Challenge. For details, see: August More Text Challenge.”

TS 1.5 starts with an internal module represented by a namespace and an external module represented by a module.

Usage scenarios

Take a document for example: a document can be considered a module

As more code grows in files, we want to have some organizational standard that can track types and not worry about naming conflicts. You can solve this problem by including objects in a namespace (not a global namespace).

index.ts

namesapce validator{
    class Val{}
}
Copy the code

Objects can be accessed from within the file via validator.val. If you want to access the file outside, you need to add the export keyword.

Document segmentation

When your application is bloated, you should break up the code into separate files for easier maintenance.

Multi-file namespaces

When files are split, each file creates the same namespace, and the namespaces in these files need to be connected and accessed. Behaviorally, as before in the same document. Therefore, reference tags need to be added.

index1.ts

namespace NS{
    class Val1{}
}
Copy the code

index2.ts

/// <reference path="index1.ts"/>
namespace NS{
    class Val2{}
}
Copy the code

impl.ts

/// <reference path="index1.ts">
/// <reference path="index2.ts">

let val1 = new NS.Val1()
Copy the code

Once multiple files are involved, we must ensure that the code for each file is compiled. There are two ways to make sure:

–outFile

Method 1: Use –outFile to compile all files into one file. The compiler automatically compiles the referenced files in order.

tsc --outFile sample.js impl.ts
Copy the code

Method 2:

Of course, you can also do this manually using the following command and end up with multiple files.

tsc --outFile sample.js index1.ts index2.ts impl.ts
Copy the code

Because you get multiple compiled files, you need to use them when you use them

<script src="index1.js" type="text/javascript" /><script src="index2.js" type="text/javascript" /><script src="impl.js" type="text/javascript" />
Copy the code

The alias

You can use import = A.B.C to create an alias for the namespace. Note the difference with import = require(” XXX “).

namespace Shapes{
    export namespace Polynes{
        class Square()
    }
}

import polynes = Shapes.Polynes

const square = new polynes.Square() // Same as 'new Shapes.Polygons.Square()'
Copy the code

Be careful not to use the require keyword.

Ambient Namespaces

D3 defines the global object D3. Because using D3 is through

declare namespace D3{
    export interface Selectors{}
    export interface Event{
        x: number
    }
    export interface Base extends Selector(){
        event: Event
    }
}

declare var d3: D3.base
Copy the code