Does TypeScript Namespace Support?

Like the title: Does TypeScript support a namespace? If so, how to use them?

+52
namespaces typescript
Oct 05
source share
5 answers

Typescript allows you to define modules that are closely related to what will happen in ECMAScript 6. The following example is taken from the specification:

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 periods in module names, typescript compiles this for nested modules as follows:

 module ABC { export var x = 1; } 

It is equal

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

It is also important that if you reuse the same module name in the same typescript program, the code will belong to the same module. Therefore, you can use nested modules to implement hierarchical namespaces.

+55
Oct 05 '12 at 8:12
source share

Starting with version 1.5, Typescript supports the 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) { ... } } 

You can now use both module and namespace to define an internal module.

+28
Jul 24 '15 at 18:01
source share

Here is an example TypeScript space:

 ///<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 find out more here: http://www.codebelt.com/typescript/javascript-namespacing-with-typescript-internal-modules/

+9
Nov 03 '13 at 21:54
source share

There is no keyword "namespace", but internal modules (using the keyword "module") and external modules (using the keyword "export") offer a similar way to split your code into logical hierarchies.

+7
Oct 05
source share

False ...

 module ABC { export var x = 1; } 

equally

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

because you can write outside module A:

 var y = ABCx; 

But:

 module A { module B { module C { export var x = 1; } var y = Cx; // OK } //var y = BCx; // Invalid } //var y = ABCx; // Invalid 
+3
Jul 21 '15 at 11:45
source share



All Articles