In this tutorial, we will dive into the concept of Namespaces in TypeScript. We will discover how to use namespaces to organize our code, prevent naming collisions, and enhance our code readability.
You will learn:
- What namespaces are and their importance
- How to declare and use namespaces
- Best practices when working with namespaces
Prerequisites:
- Basic knowledge of TypeScript
- A development environment set up with TypeScript installed
Namespaces are a TypeScript-specific way to organize your code. They are essentially a way to group related code under a common name, to avoid naming collisions and make code more readable.
In TypeScript, a namespace is defined using the namespace
keyword, followed by the name of the namespace and a set of curly braces {}
. The code that belongs to the namespace goes inside these braces.
namespace MyNamespace {
// code goes here
}
To use a function or variable from a namespace, you prefix it with the namespace name followed by a dot .
.
namespace MyNamespace {
export function displayMessage() {
console.log("Hello from MyNamespace!");
}
}
MyNamespace.displayMessage(); // Outputs: "Hello from MyNamespace!"
Let's look at a more practical example:
namespace StringUtilities {
export function toUpperCase(str: string): string {
return str.toUpperCase();
}
export function toLowerCase(str: string): string {
return str.toLowerCase();
}
}
console.log(StringUtilities.toUpperCase("hello")); // Outputs: "HELLO"
console.log(StringUtilities.toLowerCase("WORLD")); // Outputs: "world"
In this example, we have a namespace StringUtilities
that contains two functions: toUpperCase
and toLowerCase
. The export
keyword is used to make these functions available outside the namespace.
In this tutorial, we learned about namespaces in TypeScript. We learned how to declare, use, and organize code using namespaces. We also covered some best practices when working with namespaces.
For further learning, explore how namespaces can be split across many files and how to use /// <reference>
directive for this purpose.
Create a namespace named MathUtilities
with functions to add, subtract, multiply, and divide two numbers.
Create a namespace named ArrayUtilities
that includes functions to find the minimum and maximum number in an array.
Solutions
1. MathUtilities
namespace MathUtilities {
export function add(a: number, b: number): number {
return a + b;
}
export function subtract(a: number, b: number): number {
return a - b;
}
export function multiply(a: number, b: number): number {
return a * b;
}
export function divide(a: number, b: number): number {
return a / b;
}
}
namespace ArrayUtilities {
export function findMin(arr: number[]): number {
return Math.min(...arr);
}
export function findMax(arr: number[]): number {
return Math.max(...arr);
}
}
Try to use these namespaces and functions in your code.
Remember, the more you practice, the more comfortable you will become with namespaces in TypeScript. Happy coding!