TypeScript
/Intermediate
Namespaces
Definition
A TypeScript-specific way to organize code before ES Modules became the standard. They group logically related code under a single global object.
Explain Like I'm New
Before modern JavaScript `import/export` existed, if you had two functions named `calculate()`, they would clash. Namespaces were TS's solution to group them: `MathUtils.calculate()` and `PhysicsUtils.calculate()`. Today, they are largely obsolete.
Real World Example
You will mostly see Namespaces in legacy codebases, or when writing Declaration Files (`.d.ts`) to describe old JavaScript libraries (like jQuery) that attach themselves globally to the `window` object.
Common Use Cases
- •Legacy code support
- •Typing global `<script>` tag libraries
Interactive Example
// DEFINITION namespace Validation { // Must export the interface to be visible outside the namespace export interface StringValidator { isAcceptable(s: string): boolean; } const lettersRegexp = /^[A-Za-z]+$/; // Must export the class too export class LettersOnlyValidator implements StringValidator { isAcceptable(s: string) { return lettersRegexp.test(s); } } } // USAGE (Accessed via dot notation) const myValidator = new Validation.LettersOnlyValidator(); myValidator.isAcceptable("Hello"); // true
Interview Questions
basic
- Should you use Namespaces for new TypeScript projects?
intermediate
- How do you access a function inside a Namespace?
advanced
- What is the difference between a Namespace and a Module?