How to create a TypeScript namespace



Image not found!!

In TypeScript, namespaces are used to organize code and prevent naming conflicts. They are similar to modules but have a different syntax. To create a TypeScript namespace, you can follow these steps:

  1. Create a TypeScript file (e.g., example.ts):
typescript
// example.ts // Define a namespace namespace MyNamespace { // Declare variables, functions, classes, etc. within the namespace export const myVariable: number = 42; export function myFunction(): void { console.log("Hello from myFunction!"); } export class MyClass { constructor(private name: string) {} public greet(): void { console.log(`Hello, ${this.name}!`); } } } // Use the elements defined in the namespace console.log(MyNamespace.myVariable); MyNamespace.myFunction(); const myInstance = new MyNamespace.MyClass("John"); myInstance.greet();
  1. Compile the TypeScript code:

You need to compile the TypeScript code into JavaScript using the TypeScript compiler (tsc). If you don't have TypeScript installed, you can install it globally using:

bash
npm install -g typescript

Then, compile your TypeScript file:

bash
tsc example.ts
  1. Include the generated JavaScript file in your HTML or import it in another TypeScript file:
html
<!-- index.html --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>TypeScript Namespace Example</title> </head> <body> <!-- Include the generated JavaScript file --> <script src="example.js"></script> </body> </html>
  1. Run the HTML file in a browser:

Open the HTML file in a web browser, and you should see the output in the browser's console.

This example demonstrates how to create a namespace (MyNamespace) and define variables, functions, and a class within it. You can then access and use these elements outside the namespace by referencing the namespace name.