TypeScript namespace explanation

TypeScript namespace explanation

Preface:

namespace were called internal modules before TypeScript 1.5 because modules in ES6 were not yet a formal standard. When ES6 proposed the specification, TypeScript 1.5 officially changed its name to namespaces and used namespace to define them.

1. Definition and Use

1.1 Definition

The definition of a namespace is equivalent to defining an object, in which variables, interfaces, classes, methods, etc. can be defined. However, if the export keyword is not used to specify that this content is externally visible, it cannot be accessed from the outside.

Next, define a .ts file for regular validation. The implementation code is as follows:

// validation.ts
// Create a namespace named Validation through namespace namespace Validation {
    // Define a regular expression const isLetterReg = /^[A-Za-z]+$/
    // Here we define a regular expression. The difference from the previous one is that this regular expression is exported through export const isNumberReg = /^[0-9]+$/
    // Export a method export const checkLetter = (text: any) => {
        return isLetterReg.test(text)
    }
}

In the above code, we define a namespace called Validation , define two properties and one method in it, and export one property and one method (the export keyword is used in the namespace export).

1.2 Use

To use the content in a namespace in a file, just use /// <reference path=“namespace.ts”/> to introduce it where the external namespace is used. Note the triple slash /// at the beginning, and then specify the path of the namespace file relative to the current file in the path attribute. The specific code is as follows:

// index.ts
/// <reference path='validation.ts' />
let isLetter = Validation.checkLetter('text')
const reg = Validation.isNumberReg
console.log(isLetter)
console.log(reg)

Note /// <reference path='validation.ts' /> in the first line. The grammatical structure cannot be wrong, otherwise the compilation will fail.

The compilation command is as follows:

tsc --outFile src/index.js index.ts


The outFile parameter is used to merge the output files into one file

The compiled index.js file is as follows:

//Create a namespace named Validation through namespace var Validation;
(function (Validation) {
    // Define a regular expression var isLetterReg = /^[A-Za-z]+$/;
    // Here we define a regular expression. The difference from the previous one is that this regular expression is exported through export. Validation.isNumberReg = /^[0-9]+$/;
    // Export a method Validation.checkLetter = function (text) {
        return isLetterReg.test(text);
    };
})(Validation || (Validation = {}));
/// <reference path='validation.ts' />
var isLetter = Validation.checkLetter('text');
var reg = Validation.isNumberReg;
console.log(isLetter);
console.log(reg);

2. Split into multiple files

As our development content continues to increase, we can split the same namespace into multiple files for separate maintenance. Although we split it into multiple files, they still belong to one namespace.

The sample code is as follows:

LetterValidation.ts

// LetterValidation.ts
namespace Validation {
    export const isLetterReg = /^[A-Za-z]+$/
    export const checkLetter = (text: any) => {
        return isLetterReg.test(text)
    }
}

NumberValidation.ts

// NumberValidation.ts
namespace Validation {
    export const isNumberReg = /^[0-9]+$/
    export const checkNumber = (text: any) => {
        return isNumberReg.test(text)
    }
}

index.ts

// index.ts
/// <reference path="./LetterValidation.ts"/>
/// <reference path="./NumberValidation.ts"/>
let isLetter = Validation.checkLetter('text')
const reg = Validation.isNumberReg
console.log(isLetter)

We compile it using the command line:

tsc --outFile src/index.js index.ts


The final compiled index.js code is as follows:

// LetterValidation.ts
var Validation;
(function (Validation) {
    Validation.isLetterReg = /^[A-Za-z]+$/;
    Validation.checkLetter = function (text) {
        return Validation.isLetterReg.test(text);
    };
})(Validation || (Validation = {}));
// NumberValidation.ts
var Validation;
(function (Validation) {
    Validation.isNumberReg = /^[0-9]+$/;
    Validation.checkNumber = function (text) {
        return Validation.isNumberReg.test(text);
    };
})(Validation || (Validation = {}));
/// <reference path="./LetterValidation.ts"/>
/// <reference path="./NumberValidation.ts"/>
var isLetter = Validation.checkLetter('text');
var reg = Validation.isNumberReg;
console.log(isLetter);

It can be seen from the compilation results that we first introduced the LetterValidation.ts file and then the NumberValidation.ts file. Their final compiled results are also compiled in the order of introduction.

3. Aliases

Aliases are a way to simplify namespace operations. The syntax is to use the import keyword. The usage is as follows:

import q = xyz


It is worth noting that this method should not be confused with the import x = require('name') syntax of the parent module. The syntax here creates an alias for the specified symbol. This method can be used to create aliases for any identifier, including objects imported into modules.

// Define a namespace namespace Shapes {
    // Define a subnamespace in the namespace and export it export namespace Polygons {
        export class Triangle {}
        export class Square {}
    }
}
// Rename the exported subnamespace to polygons using import syntax
import polygons = Shapes.Polygons
// Instantiate the Square class from the exported namespace let sq = new polygons.Square()

From this example, we can see that using the import keyword to define an alias for an output element in a namespace can reduce the cost of obtaining attributes at a deeper level.

This is the end of this article about TypeScript namespaces. For more information about TypeScript namespaces, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • A brief analysis of TypeScript namespace
  • TypeScript namespace merging explained

<<:  Solution to HTML encoding problem in IE6 that causes JS error and CSS not being applied

>>:  In-depth analysis of HTML semantics and its related front-end frameworks

Recommend

How to perform query caching in MySQL and how to solve failures

We all know that we need to understand the proper...

Solution to MySql service disappearance for unknown reasons

Solution to MySql service disappearance for unkno...

JavaScript timer to achieve seamless scrolling of pictures

This article shares the specific code of JavaScri...

Introduction to useRef and useState in JavaScript

Table of contents 1. useState hook 2. useRef hook...

Installation and configuration of MySQL 5.7.17 free installation version

MYSQL version: MySQL Community Server 5.7.17, ins...

Running PostgreSQL in Docker and recommending several connection tools

1 Introduction PostgreSQL is a free software obje...

Vue image cropping component example code

Example: tip: This component is based on vue-crop...

Docker's health detection mechanism

For containers, the simplest health check is the ...

Vue Page Stack Manager Details

Table of contents 2. Tried methods 2.1 keep-alive...

Learn the basics of nginx

Table of contents 1. What is nginx? 2. What can n...

Using HTML+CSS to track mouse movement

As users become more privacy-conscious and take m...

How to install MySQL 5.7 on Ubuntu and configure the data storage path

1. Install MySQL This article is installed via AP...

Detailed explanation of SELINUX working principle

1. Introduction The main value that SELinux bring...