Friday, November 16, 2018

TypeScript - Namespaces - nested namespaces and import alias

In TypeScript, it is possible to include a namespace inside another namespace. This is called nesting of namespaces. Consider the file:

circleArea.ts
namespace myArea {
const PI = Math.PI;
export function circleArea(radius: number){
return PI*radius*radius;
}
}

We can rewrite it to include a circleStuff namespace inside it. 

namespace myArea {
namespace circleStuff {
const PI = Math.PI;
export function circleArea(radius: number){
return PI*radius*radius;
}
}
}

To be able the circleStuff namespace, we must export it - or else, it will be private. Hence, we have to rewrite it again as follows:

namespace myArea {
export namespace circleStuff {
const PI = Math.PI;
export function circleArea(radius: number){
return PI*radius*radius;
}
}
}

To make this work, we must visit our app.ts file and include the nested namespace - circleStuff:
///<reference path="circleArea.ts"/>
///<reference path="squareArea.ts"/>
console.log(myArea.circleStuff.circleArea(5));
console.log(myArea.squareArea(5));

Now, let us compile and reload the browser:

$ tsc app.ts --outFile app.js
$ python -m SimpleHTTPServer 3000
Serving HTTP on 0.0.0.0 port 3000 ...
127.0.0.1 - - [16/Nov/2018 08:04:34] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [16/Nov/2018 08:04:34] "GET /app.js HTTP/1.1" 200 -

Console Output:
78.53981633974483
25

Also, instead if multiple chains of access, we can also create an alias for the nested namespace and then use it in the console.log to access the function using the alias. 

app.ts - rewritten
///<reference path="circleArea.ts"/>
///<reference path="squareArea.ts"/>

// aliasing for circleStuff
import circleStuffImport = myArea.circleStuff;

console.log(circleStuffImport.circleArea(5));
console.log(myArea.squareArea(5));


Now, if we compile and re-run:

$ tsc app.ts --outFile app.js
$ python -m SimpleHTTPServer 3000
Serving HTTP on 0.0.0.0 port 3000 ...
127.0.0.1 - - [16/Nov/2018 08:09:32] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [16/Nov/2018 08:09:32] "GET /app.js HTTP/1.1" 200 -


We observe the same Console Output:
78.53981633974483
25

These are the various ways in which we can use namespaces in TypeScript. 

No comments:

Post a Comment