They are common in large projects where many people work on the same codebase.

They can make it difficult to determine which code component is responsible for bugs.

This will mitigate the risk of naming conflicts.

A dark monitor displaying TypeScript code in the VSCode editor.

Use theexportkeyword to make each member of the namespace accessible outside of it.

Nesting namespaces can further reduce the risks of naming collisions by grouping related namespaces under a common identifier.

The code block above provides an example of a nested namespace.

TheExamplenamespace is the top-level namespace, containing theBarnamespace and theBaznamespace.

This example code accesses each member of the namespace via the parent namespace.

Deeply nested namespaces make your code harder to read and maintain.

Then, assign theimportkeyword and the alias name to a namespace member.

This example creates an alias for theCar.Teslanamespace.

Importing namespaces is different from importing variables, functions, classes, etc.

Depending on your project’smodule system, it’s possible for you to import them using either therequireor theimportkeyword.

This example uses the triple slash directive inside amain.tsfile.

The directive references theindex.tsfile, which contains theExamplenamespace.

Without importing, the namespace is only available within the same file that defines it.

After referencing theindex.tsfile, you’re free to access theExamplenamespace and its publicly available members.

For instance, you’ve got the option to call thefoomethod on theExamplenamespace.

you’re free to do so by concatenating output from the TypeScript compiler using theoutFileoption.

This will then compile all the input files into a single JavaScript output file.

Replace<TYPESCRIPT_FILE>with the name of the TypeScript file containing the triple-slash directive.

Should You Use Namespaces or Modules?

While namespaces arent deprecated, organizing and managing your code using ES6 modules is often recommended.

Modules are easier to maintain and manage and you might scope them across multiple files.

Namespaces cannot define their dependencies.