Modules
TS Namespaces
Using TypeScript Namespaces
TypeScript namespaces organize code though modules are recommended.
Introduction to TypeScript Namespaces
Namespaces in TypeScript are a way to organize code and avoid naming collisions in the global scope. They are often compared to modules but serve a different purpose. While modules are preferred for code organization in modern TypeScript, understanding namespaces can be beneficial, especially for legacy codebases.
Defining a Namespace
To define a namespace in TypeScript, use the namespace
keyword followed by the namespace name. Inside the curly braces, you can define functions, variables, classes, or other namespaces.
Accessing Namespace Members
To access members of a namespace, you must use the dot notation. Only the members that are explicitly marked with the export
keyword are accessible from outside the namespace.
Nesting Namespaces
Namespaces can be nested within each other to further organize code. This can be useful in large applications where logical grouping is necessary.
Merging Namespaces and Interfaces
One of the unique features of namespaces is their ability to merge with interfaces. This allows you to extend interfaces with additional properties or methods that are defined in the namespace.
When to Use Namespaces
Namespaces can be useful in scenarios where you need to organize code in a structured way without the need for module imports and exports. They are often used in legacy codebases or when working with older JavaScript libraries. However, for most modern applications, modules are preferred due to their better support in tooling and compatibility with ECMAScript standards.
Modules
- Previous
- Modules
- Next
- Module Resolution