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

Navicat multiple ways to modify MySQL database password

Method 1: Use the SET PASSWORD command First log ...

HTML tags: sub tag and sup tag

Today I will introduce two HTML tags that I don’t...

Problems with using wangeditor rich text editing in Vue

wangEditor is a web rich text editor developed ba...

jQuery achieves full screen scrolling effect

This article example shares the specific code of ...

Clever use of webkit-box-reflect to achieve various dynamic effects (summary)

In an article a long time ago, I talked about the...

WeChat applet learning wxs usage tutorial

What is wxs? wxs (WeiXin Script) is a scripting l...

Detailed explanation of keepAlive usage in Vue front-end development

Table of contents Preface keep-avlive hook functi...

Implementation of HTML sliding floating ball menu effect

CSS Styles html,body{ width: 100%; height: 100%; ...

Best Practices Guide for Storing Dates in MySQL

Table of contents Preface Do not use strings to s...

VUE implements bottom suction button

This article example shares the specific code of ...

How to use Font Awesome 5 in Vue development projects

Table of contents Install Dependencies Configurat...