- Mastering TypeScript 3
- Nathan Rozentals
- 365字
- 2021-07-02 12:42:53
Namespaces
When working with large projects, and particularly when working with external libraries, there may come a time when two classes or interfaces share the same name. This will obviously cause compilation errors. TypeScript uses the concept of namespaces to cater for these situations.
Let's take a look at the syntax used for namespaces, as follows:
namespace FirstNameSpace { class NotExported { } export class NameSpaceClass { id: number | undefined; } }
Here, we are defining a namespace using the namespace keyword, and have called this namespace FirstNameSpace. A namespace declaration is similar to a class declaration, in that it is scoped by the opening and closing braces, that is, { starts the namespace, and } closes the namespace. This namespace has two classes defined within it. These classes are named NotExported, and NameSpaceClass.
When using namespaces, a class definition will not be visible outside of the namespace, unless we specifically allow this using the export keyword. To create classes that are defined within a namespace, we must reference the class using the full namespace name. Let's take a look at how we would create instances of these classes:
let firstNameSpace = new FirstNameSpace.NameSpaceClass(); let notExported = new FirstNameSpace.NotExported();
Here, we are creating an instance of NameSpaceClass, and an instance of the NotExported class. Note how we need to use the full namespace name in order to correctly reference these classes, that is, new FirstNameSpace.NameSpaceClass(). As the NotExported class has not used the export keyword, the last line of this code will generate the following error:
error TS2339: Property 'NotExported' does not exist on type 'typeof FirstNameSpace'.
We can now introduce a second namespace, as follows:
namespace SecondNameSpace { export class NameSpaceClass { name: string | undefined; } } let secondNameSpace = new SecondNameSpace.NameSpaceClass();
This namespace also exports a class that is named NameSpaceClass. On the last line of this code snippet, we are again creating an instance of this class using the full namespace name, that is, new SecondNameSpace.NameSpaceClass();. Using the same class name in this instance will not cause compilation errors, as each class (prefixed by the namespace name) is seen by the compiler as a separate class name.