4.2 Declaring namespaces & legacy internal modules

Namespaces are a kind of internal module. Namespaces were known as internal modules, in the past it caused some confusion within the TypeScript community and the TypeScript team decided to change their name to make them easier to understand.

Getting Ready

All you need to implement in this recipe is an installation of TypeScript 2.0 or higher.

How to do it

You can declare a using the namespace keyword:

namespace MyLybrary {
   export function someFunction(x, y) {
	  //...
	}
}

Namespaces used the module keyword before it was renamed by the TypeScript team:

namespace MyLybrary {
   export function someFunction(x, y) {
	  //...
	}
}

How it works

Both, the legacy syntax (module keyword) and the new syntax (namespace keyword) can be used at design time and generate the same JavaScript code:

var MyLybrary;
(function (MyLybrary) {
    function someFunction(x, y) {
      // ...
    }
    MyLybrary.someFunction = someFunction;
})(MyLybrary || (MyLybrary = {}));
Since the module keyword will potentially become deprecated at some stage you should try to use the namespace keyword rather than the module keyword.

As we can observe in the preceding code snippet, the TypeScript compiler uses an immediately-invoked function expression (IIFE) to wrap the contents of the module or namespace and declares a variable named MyLybrary in the global scope. When the first module is loaded MyLybrary is undefined and it will be initialize using an empty object literal:

(MyLybrary = {})

When other modules are loaded, the MyLybrary object will already be defined and the contents of the new module contents will be appended to it as properties.

Note that only the elements flagged with the export keyword are accessible from the outside of a module.

There’s more

Namespaces can contain sub-namespaces. To declare a sub-namespace, you can use the dot character when declaring the module name:

namespace MyLybrary.SubNamespace {
    export function someFunction(x, y) {	
      // ...
    }
}

Alternatively, you can declare nested namespaces:

namespace MyLybrary {
    namespace SubNamespace  {
		export function someFunction(x, y) {
			// ...
		}
	}
}

The two preceding code snippet generates the same code snippet:

var MyLybrary;
(function (MyLybrary) {
    var SubNamespace;
    (function (SubNamespace) {
        function someFunction(x, y) {
          // ...
        }
        SubNamespace.someFunction = someFunction;
    })(SubNamespace = MyLybrary.SubNamespace || (MyLybrary.SubNamespace = {}));
})(MyLybrary || (MyLybrary = {}));

See also

You can refer to the recipe about importing namespaces to learn how to consume internal modules after declaring them.


Shiv Kushwaha

Author/Programmer