Namespaces in TypeScript

  • Namespace is used to group logically related code.
  • When we have multiple files with globally declared variables, there may be a possibility of overwriting or misusing these variables.
  • We use namespaces to solve this issue.
  • Namespace definition begins with namespace keyword followed by the namespace name.
  • Syntax: namespace namespaceName{ //code for namespace }
  • We define classes and interfaces within a namespace.
  • If we want to access these classes and interfaces from outside of namespace, they should be exported using export keyword.
  • To access the class or interface from another namespace, we use this syntax: namespaceName.className;

Below is the example
We have created two files: Namespace1.ts and Namespace2.ts

Namespace1.ts
namespace namespace1{
    export class Car{
        model:string;
        color:string;
        constructor(m:string, c:string){
            this.model = m;
            this.color = c;
        }
        carDetails():void{
            console.log(this.model + " is available in " + this.color + " color.")
        }
    }
    var myCar = new Car("Swift","Silver");
    myCar.carDetails();
}
Namespace2.ts
/// <reference path = "Namespace1.ts" />
namespace namespace2{
    console.log("\nIn Namespace2.ts file");
    var maruti = new namespace1.Car("Brezza","White");
    maruti.carDetails();
}

Now open Node.js Command Prompt and type the following two commands

tsc --out myjsfile.js Namespace2.ts
node myjsfile.js

Below is the output in Node.js Command Prompt

Power Platform Academy

Start or Upgrade your Career with Power Platform

Learn with Akanksha

Python | Azure | AI/ML | OpenAI | MLOps

Design a site like this with WordPress.com
Get started