Namespaces

A namespace organizes and groups related code together under a named scope. They are used to avoid name collisions in the global scope by wrapping variables, functions, classes, or interfaces in a container.

Creating a namespace

The namespace keyword is used to define a namespace. Inside the namespace, you can declare types, interfaces, classes, or functions the same way as you would in the global scope.

Loading TypeScript...

By default, members of a namespace are not accessible outside of it unless they are explicitly marked with the export keyword. In the example above, both functions are exported, so you can call them from outside using the namespace Validator as a qualifier.

You can also nest namespaces to create hierarchical structures, which is especially useful for logically separating submodules or internal details.

Namespaces can be split across multiple files by using the same name in each file. As long as the files are compiled together (e.g., by listing them explicitly in the compiler options or using triple-slash directives), TypeScript can merge the declarations into a single namespace.

Modules vs namespaces

When working in a module-based system, like ES modules or when using import and export, TypeScript prefers modules over namespaces. If you're using files with top-level import or export, you should avoid namespaces and instead use module exports to group related code.

Namespaces are often used in projects that target environments without module loaders, or when compiling down to a single JavaScript file. They are also helpful when structuring code for in-browser execution without bundlers.

Was this page helpful?