Organizing TypeScript code using namespaces

mangelosanto

Matt Angelosanto

Posted on August 16, 2021

Organizing TypeScript code using namespaces

Written by Emmanuel John ✏️

Introduction

With the use of third-party libraries in enterprise software increasing, we often encounter the problem of polluted global namespaces, causing name collision between components in the global namespace. Therefore, we need to organize blocks of code using namespaces so that variables, objects, and classes are uniquely identified.

In this article, we will discuss namespaces, when you'll need them, and how to use them to enhance the organization of your TypeScript code.

Prerequisites

  • Knowledge of TypeScript
  • Familiarity with JavaScript

What are namespaces?

Namespaces are paradigm of organizing code so that variables, functions, interfaces, or classes are grouped together within a local scope in order to avoid naming conflicts between components in the global scope. This is one of the most common strategies to reduce global scope pollution.

While modules are also used for code organization, namespaces are easy to use for simple implementations. Modules offer some additional benefits like strong code isolation, strong support for bundling, re-exporting of components, and renaming of components that namespaces do not offer.

Why do we need namespaces?

Namespaces have these advantages:

  • Code reusability — The importance of namespaces for code reusability cannot be understated
  • Bloated global scope — Namespaces reduce the amount of code in the global scope, making it less bloated
  • Third-party libraries — With the increasing number of websites depending on third-party libraries, it's important to safeguard your code using namespaces to prevent same-name conflicts between your code and the third-party libraries
  • Distributed development — With distributed development becoming popular, pollution is almost unavoidable because it’s a lot easier for developers to use common variable or class names. This results in name collision and pollution of the global scope

Design considerations using namespaces

Implicit dependency order

Using namespaces while working with some external libraries will require an implicit implementation of dependency between your code and these libraries. This results in the stress of managing the dependencies yourself so that they are loaded correctly, because the dependencies can be error-prone.

If you find yourself in such a situation, using modules will save you the stress.

Node.js applications

For Node.js applications, modules are recommended over namespaces since modules are the de facto standard for encapsulation and code organization in Node.

Non-JavaScript content import

Modules are recommended over namespaces when dealing with non-JavaScript content since some module loaders such as SystemJS and AMD allow non-JavaScript content to be imported.

Legacy code

When working with a codebase that is no longer engineered but continually patched, using namespaces is recommended over modules.

Also, namespaces come in handy when porting old JavaScript code.

Exploring namespaces in TypeScript

Now that we have a shared understanding of what TypeScript namespaces are and why we need them, we can take a deeper dive into how to use them.

Given that TypeScript is a superset of JavaScript, it derives its namespace concept from JavaScript.

By default, JavaScript has no provision for namespacing because we have to implement namespaces using IIFE (Immediately Invoked Function Expression):

var Vehicle;
(function (Vehicle) {
    let name = "car";
})(Vehicle || (Vehicle = {}));
Enter fullscreen mode Exit fullscreen mode

This is so much code for defining a namespace. Meanwhile, TypeScript does things differently.

Single-file namespacing

In TypeScript, namespaces are defined using the namespace keyword followed by a name of choice.

A single TypeScript file can have as many namespaces as needed:

namespace Vehicle {}
namespace Animal {}
Enter fullscreen mode Exit fullscreen mode

As we can see, TypeScript namespaces are a piece of syntactic cake compared to our JavaScript implementation of namespaces using the IIFE.

Functions, variables, and classes can be defined inside a namespace as follows:

namespace Vehicle {
  const name = "Toyota"
  function getName () {
      return `${name}`
  }
}
namespace Animal {
  const name = "Panda"
  function getName () {
      return `${name}`
  }
}
Enter fullscreen mode Exit fullscreen mode

The above code allows us to use the same variable and function name without collision.

Accessing functions, variables, objects, and classes outside a namespace

In order to access functions or classes outside their namespaces, the export keyword must be added before the function or class name as follows:

namespace Vehicle {
  const name = "Toyota"
  export function getName () {
      return `${name}`
  }
}
Enter fullscreen mode Exit fullscreen mode

Notice that we had to omit the export keyword with the variable because it should not be accessible outside the namespace.

Now, we can access the getName function as follows:

Vehicle.getName() //Toyota
Enter fullscreen mode Exit fullscreen mode

Organizing code using nested namespaces

TypeScript allows us to organize our code using nested namespaces.

We can create nested namespaces as follows:

namespace TransportMeans {
  export namespace Vehicle {
    const name = "Toyota"
    export function getName () {
        return `${name}`
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Notice the export keyword before the Vehicle namespace. This allows the namespace to be accessible outside of the TransportMeans namespace.

We can also perform deep nesting of namespaces.

Our nested namespaces can be accessed as follows:

TransporMeans.Vehicle.getName() // Toyota
Enter fullscreen mode Exit fullscreen mode

The namespace alias

For deeply nested namespaces, the namespace alias comes in handy to keep things clean.

Namespace aliases are defined using the import keyword as follows:

import carName= TransporMeans.Vehicle;
carName.getName(); //Toyota
Enter fullscreen mode Exit fullscreen mode

Multi-file namespacing

Namespaces can be shared across multiple TypeScript files. This is made possible by the reference tag.

Considering the following:

//constant.ts
export const name = "Toyota"

//vehicle.ts
<reference path = "constant.ts" />
export namespace Vehicle {
  export function getName () {
      return `${name}`
  }
}
Enter fullscreen mode Exit fullscreen mode

Here, we had to reference the constant.ts file in order to access name:

//index.ts
<reference path = "constant.ts" />
<reference path = "vehicle.ts" />
Vehicle.getName() // Toyota
Enter fullscreen mode Exit fullscreen mode

Notice how we started our references with the highest-level namespace. This is how to handle references in multi-file interfaces. TypeScript will use this order when compiling the files.

We can instruct the compiler to compile our multi-file TypeScript code into a single JavaScript file with the following command:

 tsc --outFile index.js index.ts
Enter fullscreen mode Exit fullscreen mode

With this command, the TypeScript compiler will produce a single JavaScript file called index.js.

Conclusion

In order to build scalable and reusable TypeScript applications, TypeScript namespaces are handy because they improve the organization and structure of our application.

In this article, we’ve been able to explore namespaces, when you need them, and how to implement them. Check out TypeScript Handbook: Namespaces for more information about namespaces.


LogRocket: Full visibility into your web apps

LogRocket Dashboard Free Trial Banner

LogRocket is a frontend application monitoring solution that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets you replay the session to quickly understand what went wrong. It works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and ngrx/store.

In addition to logging Redux actions and state, LogRocket records console logs, JavaScript errors, stacktraces, network requests/responses with headers + bodies, browser metadata, and custom logs. It also instruments the DOM to record the HTML and CSS on the page, recreating pixel-perfect videos of even the most complex single-page apps.

Try it for free.

💖 💪 🙅 🚩
mangelosanto
Matt Angelosanto

Posted on August 16, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related