Does TypeScript support namespace?

As in the title: does TypeScript support namespaces? If so, how do I use them?


Typescript allows to define modules closely related to what will be in ECMAScript 6. The following example is taken from the spec:

module outer {
    var local = 1;
    export var a = local;
    export module inner {
        export var x = 10;
    }
}

As you can see, modules have names and can be nested. If you use dots in module names, typescript will compile this to nested modules as follows:

module A.B.C {
    export var x = 1;
}

This is equal to

module A {
    module B {
        module C {
            export var x = 1;
        }
    }
}

What's also important is that if you reuse the exact same module name in one typescript program, the code will belong to the same module. Hence, you can use nested modules to implement hierarchichal namespaces.


As of version 1.5, Typescript supports namespace keyword. Namespaces are equivalent to internal modules.

From What's new in Typescript:

Before:

module Math {
    export function add(x, y) { ... }
}

After:

namespace Math {
    export function add(x, y) { ... }
}

For defining an internal module, now you can use both module and namespace.


Here is a TypeScript namespace example:

///<reference path='AnotherNamespace/ClassOne.ts'/>
///<reference path='AnotherNamespace/ClassTwo.ts'/>

module MyNamespace
{
    import ClassOne = AnotherNamespace.ClassOne;
    import ClassTwo = AnotherNamespace.ClassTwo;

    export class Main
    {
        private _classOne:ClassOne;
        private _classTwo:ClassTwo;

        constructor()
        {
            this._classOne = new ClassOne();
            this._classTwo = new ClassTwo();
        }
    }
}

You can check out more here:http://www.codebelt.com/typescript/javascript-namespacing-with-typescript-internal-modules/