Thursday, November 15, 2018

TypeScript - Namespaces - Introductory Example

Consider the following code snippet which includes functions to calculate the area of:

  • Circle
  • Square

app.ts:  -- does not include namespace
function circleArea(radius: number){
return Math.PI*radius*radius;
}

function squareArea(sideLength:number){
return sideLength*sideLength;
}

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

Now, when we write code like this. There are too many functions in the global scope. There are scenarios where we would like to group related functions. For example, in this scenario both these functions are calculating the area. Hence, we can combine them both into a single module. This facility provided by TypeScript to group similar code stuff is namespace.

Consider the following code snippet - which just the above code rewritten:

app.ts - includes namespace
namespace myArea {
const PI = Math.PI;
export function circleArea(radius: number){
return PI*radius*radius;
}
export function squareArea(sideLength:number){
return sideLength*sideLength;
}
}
console.log(myArea.circleArea(5));
console.log(myArea.squareArea(5));

In this, we are grouping the functions into a bigger umbrella and terming it as myArea namespace. Please note that the individual functions and variables need to be exported - so that we can use it outside the namespace. In the above code snippet, exported properties are:

##
object-type
object-name

1 variable
PI
not exported
2 function
circleArea
exported
3 function squareArea
exported



Below is console output:

78.53981633974483
25


Reference:

No comments:

Post a Comment