“This is the 18th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021”

preface

In the previous two articles, we showed you how to use namespaces in TS to organize your code, mainly using the namespace keyword in the following format: namespace X {}, and we solved a legacy problem: we split large single files into different files as needed

Portal:

  • TS separates a single file into different files
  • How do you use namespaces in TS to organize your code

Today’s lecture is also namespace-related, a way to simplify operations on namespaces

The cause of

We often have trouble using things in a namespace, such as the following:

namespace Shapes {
    export namespace Polygons {
        export class Triangle {}export class Square {}}}Copy the code

If we were to use Triangle or Square inside, we would look something like this:

new Shapes.Polygons.Triangle();
new Shapes.Polygons.Square();
Copy the code

You can see there’s a bunch behind it. It’s too long

That’s what we’re going to do, simplify the namespace

Simplified namespace

The key to simplifying namespaces is to give commonly used objects short names

TS uses import to create an alias for the specified symbol, in the format of import q = X.Y.Z

It’s a bit like VAR, but it also applies to types and imported symbols with namespace meaning, and for values, import generates a different reference than the original symbol

Here we use the import to simplify the code:

import polygons = Shapes.Polygons;
Copy the code

And then it becomes very simple to use

new polygons.Square();
// Shapes new Shapes.polygons.square ();
Copy the code

And, no matter how long, it’s so simple

Note that instead of using the require keyword, we assign directly using the qualified name of the import symbol. Not to be confused with the import x = require(‘name’) syntax used to load modules

END

That’s all for this article. If you have any questions, please point out