Namespaces in TypeScript
In this tutorial, we will explore namespaces in TypeScript. Understanding the purpose of namespaces and how to use them effectively will help you manage your code, enabling better organization, collaboration, and maintainability.
What are Namespaces?
Namespaces in TypeScript are a way to group related code, helping you avoid naming collisions and organize your codebase. Namespaces can contain variables, functions, classes, interfaces, and even other namespaces. They are particularly useful in large projects or when working with third-party libraries.
Creating a Namespace
To create a namespace, use the namespace
keyword followed by the desired name:
namespace Animals {
export class Dog {
constructor(public name: string) {}
bark() {
console.log(`${this.name} says woof!`);
}
}
export class Cat {
constructor(public name: string) {}
meow() {
console.log(`${this.name} says meow!`);
}
}
}
In this example, we create a namespace called Animals
containing two classes, Dog
and Cat
. Notice that we use the export
keyword to make the classes available outside the namespace.
Using a Namespace
To use elements from a namespace, you can reference them using the namespace's name followed by a dot:
const dog = new Animals.Dog('Buddy');
dog.bark(); // Output: Buddy says woof!
const cat = new Animals.Cat('Whiskers');
cat.meow(); // Output: Whiskers says meow!
In this example, we create instances of the Dog
and Cat
classes from the Animals
namespace.
Splitting Namespaces Across Files
You can split a namespace across multiple files using the ///<reference />
directive:
// animals/dog.ts
///<reference path="./cat.ts" />
namespace Animals {
export class Dog {
// ...
}
}
// animals/cat.ts
namespace Animals {
export class Cat {
// ...
}
}
In this example, we split the Animals
namespace into two separate files, dog.ts
and cat.ts
. The ///<reference />
directive in dog.ts
ensures that TypeScript includes the cat.ts
file when compiling the code.
Conclusion
In this tutorial, we have explored namespaces in TypeScript. Understanding the purpose of namespaces and how to use them effectively will enable you to manage your code, improving organization, collaboration, and maintainability.