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:
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();
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:
bashnpm install -g typescript
Then, compile your TypeScript file:
bashtsc example.ts
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>
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.