This is the 10th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021
Examples of TypeScript
TypeScript namespaces.Copy the code
The namespace
In TypeScript, namespaces are used to avoid global contamination. Namespaces are declared with the namespace keyword. Namespaces can wrap code around and expose only objects that need to be accessed externally.
You can define any variable inside a namespace, but by default, you can only use it inside a namespace. If external variables need to be used inside the namespace, use the export keyword to export them.
/ / 1
class Mask {
// todo
}
class Content {
// todo
}
class Create {
constructor() {
new Mask();
newContent(); }}Copy the code
Example 1 defines Mask, Content, and Create classes, but in the end only one class, Create, is really used. Because the variables corresponding to the three classes are global, too much code can cause problems such as variable conflicts.
/ / 2
// Declare a namespace
namespace Model {
class Mask {
// todo
}
class Content {
// todo
}
export class Create {
constructor() {
new Mask();
newContent(); }}}// Use the namespace
new Model.Create();
Copy the code
Example 2 uses namespace optimization to optimize example 1’s code by placing all three global variables in the Model command space, making the three global variables one variable. Use the export keyword to expose the necessary Create() method, which is accessed directly through the namespace name.
The benefit of namespaces is that they give us a modularity-like approach to development, allowing us to declare as few global variables as possible. Encapsulate a group of related content together to provide a unified exposed interface to the outside world.
Namespace splitting
When the amount of code in a namespace increases, we can consider splitting the namespace.
/ / 3
/ / modelMask. Ts file
namespace Model {
const show = false;
const backgroundColor = '# 000';
export class Mask {
// todo}}/ / modelContent. Ts file
namespace Model {
const maxWidth = 500;
const backgroundColor = '#fff';
export class Content {
// todo}}Copy the code
Both the modelmask. ts file and the modelContent.ts file have a namespace named Model. It is equivalent to a namespace distributed in two TS files, sharing a namespace.
Differences between namespaces and modules
Namespace: An internal module used to organize code and avoid naming conflicts. Module: Short for TypeScript external modules that focus on code reuse. A module may have multiple namespaces.
Finish this! If this article helps you at all, please give it a thumbs up.