Namespaces

Namespaces provide you with a convenient syntax around a common pattern used in JavaScript:

  1. (function(something) {
  2. something.foo = 123;
  3. })(something || (something = {}))

Basically something || (something = {}) allows an anonymous function function(something) {} to add stuff to an existing object (the something || portion) or start a new object then add stuff to that object (the || (something = {}) portion). This means that you can have two such blocks split by some execution boundary:

  1. (function(something) {
  2. something.foo = 123;
  3. })(something || (something = {}))
  4. console.log(something); // {foo:123}
  5. (function(something) {
  6. something.bar = 456;
  7. })(something || (something = {}))
  8. console.log(something); // {foo:123, bar:456}

This is commonly used in the JavaScript land for making sure that stuff doesn’t leak into the global namespace. With file based modules you don’t need to worry about this, but the pattern is still useful for logical grouping of a bunch of functions. Therefore TypeScript provides the namespace keyword to group these e.g.:

  1. namespace Utility {
  2. export function log(msg) {
  3. console.log(msg);
  4. }
  5. export function error(msg) {
  6. console.error(msg);
  7. }
  8. }
  9. // usage
  10. Utility.log('Call me');
  11. Utility.error('maybe!');

The namespace keyword generates the same JavaScript that we saw earlier:

  1. (function (Utility) {
  2. // Add stuff to Utility
  3. })(Utility || (Utility = {}));

One thing to note is that namespaces can be nested so you can do stuff like namespace Utility.Messaging to nest a Messaging namespace under Utility.

For most projects we recommend using external modules and using namespace for quick demos and porting old JavaScript code.