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 try to add sticky effect to your CSS

Written in front I don’t know who first discovere...

How to deploy zabbix_agent in docker

zabbix_agent deployment: Recommendation: zabbix_a...

How to create your own Docker image and upload it to Dockerhub

1. First register your own dockerhub account, reg...

WeChat applet to determine whether the mobile phone number is legal example code

Table of contents Scenario Effect Code Summarize ...

mysql splits a row of data into multiple rows based on commas

Table of contents Separation effect Command line ...

mysql8.0.11 winx64 manual installation and configuration tutorial

First of all, let me talk to you about my daily l...

Vue implements the magnifying glass function of the product details page

This article shares the specific code of Vue to i...

HTML code text box limit input text box becomes gray limit text box input

Method 1: Set the readonly attribute to true. INPU...

Pure CSS code to achieve flow and dynamic line effects

Ideas: An outer box sets the background; an inner...

Vue3 realizes the image magnifying glass effect

This article example shares the specific code of ...

Summarize some general principles of web design and production

<br />Related articles: 9 practical suggesti...

Implementation steps for enabling docker remote service link on cloud centos

Here we introduce the centos server with docker i...

Detailed explanation of Vue custom instructions and their use

Table of contents 1. What is a directive? Some co...