• Using namespaces prevents global contamination
  • Namespaces can be distributed in different files. Namespaces with the same name share the same namespace.
  • Take the following code for example,b.tsCan be used inShape.square()Call the function defined in a.ts
// a.ts
namespace Shape {
    export function square(x: number) {
        return x * x
    }
}

// b.ts
// Use the following triple slash command to merge the namespace defined by A.ts when compiling B.ts
/// <reference path="a.ts" />
namespace Shape {
    const pi = Math.PI
    export function circlr(r: number) {
        return pi * r ** 2}}Copy the code
  • When we type intsc b.tsCommand to compile,b.tsThe namespace is compiled into a function that executes immediately.
  • Global variables in both filesShapeWill be used repeatedly by the respective immediately executing functions, achieving the same namespace as described in TypeScript is co-built
// a.js
var Shape;
(function (Shape) {
    var pi = Math.PI
    function circle(r) {
        return pi * Math.pow(r, 2)
    }
    Shape.circle = circle
})(Shape || (Shape = {}))


// b.js
var Shape;
(function (Shape) {
    function square(x) {
        return x * x
    }
    Shape.square = square
})(Shape || (Shape = {}))
Copy the code

Note: With the rise of ES6, namespaces are virtually unnecessary in a modular system.