4.3 Importing namespaces & legacy internal modules

In the preceding recipe we learned how to declare namespaces and legacy internal modules let’s learn how can we import them.

Getting Ready

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

How to do it

Let’s declare the following namespaces in a file named BasicOperator.ts:

namespace MyMathLybrary.BasicOperators {
  export function sume(x, y) {
    return x + y;
  }
}

Now declare a namespace in a file named Geometry.ts

namespace MyMathLybrary.Geometry {
  export const PI = 3.1416;

  export function areaOfCircle(radious) {
    return PI * (radious * radious);
  }
}

We can then access the MyMathLybrary module from other files as follows:

///<reference path="./BasicOperators.ts"/>
///<reference path="./Geomery.ts"/>

MyMathLybrary.BasicOperators.sume(2,2);
MyMathLybrary.Geometry.areaOfCircle(2);

How it works

To access a namespace from a third file you need at a reference to the files which declare the namespaces:

///<reference path="./BasicOperators.ts"/>
///<reference path="./Geomery.ts"/>

We can then reference to the namespace and sub namespaces using the name of the namespaces:

MyMathLybrary.BasicOperators.sume(2,2);
MyMathLybrary.Geometry.areaOfCircle(2);

See also

Please refer to the preceding recipe to learn more about the declaration of namespaces and legacy internal modules.


Shiv Kushwaha

Author/Programmer