Namespaces (formerly known as "Internal Modules") provide a way to group related code, functions, interfaces, and classes under a single global name to prevent global scope pollution.
[!NOTE]
Modern TypeScript codebases strongly favor ES Modules (import/export) over namespaces. Namespaces are primarily used when organizing legacy global script libraries or complex.d.tsdeclaration files.
namespace Validation {
const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const PHONE_REGEX = /^\+?[1-9]\d{1,14}$/;
export function isValidEmail(email: string): boolean {
return EMAIL_REGEX.test(email);
}
export function isValidPhone(phone: string): boolean {
return PHONE_REGEX.test(phone);
}
// Nested Namespace
export namespace Security {
export function sanitizeInput(input: string): string {
return input.replace(/<[^>]*>/g, "");
}
}
}
// Usage
console.log("Email Valid:", Validation.isValidEmail("[email protected]"));
console.log("Phone Valid:", Validation.isValidPhone("+1234567890"));
console.log("Sanitized:", Validation.Security.sanitizeInput("<script>alert('xss')</script>Hello"));
export / import): Modules support tree-shaking, static analysis, and standard JavaScript tooling..d.ts definition files for legacy global UMD packages.namespace blocks.What keyword must be placed before a function inside a namespace to make it accessible outside the namespace? (Answer: export)
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With