📘
Namespaces and Module Organization
Intermediate
90 XP
35 min
Lesson Content
Namespaces in TypeScript
Namespaces help organize code and avoid naming conflicts. Less common in modern TypeScript but still useful.
Basic Namespace
namespace MathUtils {
export function add(a: number, b: number): number {
return a + b;
}
export function multiply(a: number, b: number): number {
return a * b;
}
}
let result = MathUtils.add(5, 3);Nested Namespaces
namespace Geometry {
export namespace Circle {
export function area(radius: number): number {
return Math.PI * radius * radius;
}
}
}Example Code
Organize code with namespaces
// Simulate namespace with object
const StringUtils = {
capitalize: (str: string) => str.charAt(0).toUpperCase() + str.slice(1),
reverse: (str: string) => str.split('').reverse().join('')
};
console.log(StringUtils.capitalize("hello"));
console.log(StringUtils.reverse("world"));Expected Output:
Hello dlrow
Study Tips
- •Read the theory content thoroughly before practicing
- •Review the example code to understand key concepts
- •Proceed to the Practice tab when you're ready to code