TypeScript Namespace
The most explicit purpose of a namespace is to solve the problem of duplicate names.
Suppose there is a situation where there are two students named Xiao Ming in a class. To clearly distinguish them, we have to use some additional information besides their names, such as their surnames (Wang Xiaoming, Li Xiaoming), or their parents' names, etc.
A namespace defines the visible scope of an identifier. An identifier can be defined in multiple namespaces, and its meanings in different namespaces are irrelevant to each other. Thus, any identifier can be defined in a new namespace, and they will not conflict with any existing identifiers, because the existing definitions are all in other namespaces.
In TypeScript, namespaces are defined usingnamespacethe following syntax:
The above defines a namespace SomeNameSpaceName. If we need to call the classes and interfaces in SomeNameSpaceName from outside, we need to add theexportkeyword.
To call it in another namespace, the syntax format is:
SomeNameSpaceName.SomeClassName;
If a namespace is in a separate TypeScript file, it should be referenced using the triple-slash ///, and the syntax format is as follows:
/// <reference path = "SomeFileName.ts" />
The following examples demonstrate the use of namespaces, defined in different files:
IShape.ts file code:
Circle.ts file code:
Triangle.ts file code:
TestShape.ts file code:
Use the tsc command to compile the above code:
tsc --out app.js TestShape.ts
Get the following JavaScript code:
JavaScript
Use the node command to view the output result:
$ node app.js Circle is drawn Triangle is drawn
Nested Namespaces
Namespaces support nesting, i.e., you can define a namespace inside another namespace.
Access to members is done using a dot.to implement it, as in the following example:
Invoice.ts file code:
InvoiceTest.ts file code:
Use the tsc command to compile the above code:
tsc --out app.js InvoiceTest.ts
Get the following JavaScript code:
JavaScript
Use the node command to view the output result:
$ node app.js 200Other Extensions