In TypeScript, namespaces provide a way to organize code by encapsulating functionality within a named scope. Namespaces help prevent naming collisions and make it easier to structure larger codebases. Here's a step-by-step guide on how to use namespaces in TypeScript:
Creating a Namespace:
namespace MyNamespace {
export interface MyInterface {
// Define interface properties and methods
name: string;
age: number;
// ...
}
export class MyClass {
// Define class properties and methods
constructor(private name: string) {}
// ...
}
export function myFunction() {
// Define functions
// ...
}
}
Accessing Members within the Namespace:
// Access interface within the namespace
let myObj: MyNamespace.MyInterface = {
name: 'John',
age: 25,
};
// Access class within the namespace
let instance = new MyNamespace.MyClass('Alice');
// Access function within the namespace
MyNamespace.myFunction();
Importing and Using Namespaces:
///
// Import the namespace
import MyNamespace = MyOtherNamespace.MyNamespace;
// Use members of the imported namespace
let obj: MyNamespace.MyInterface = { name: 'Sarah', age: 30 };
let myInstance = new MyNamespace.MyClass('Bob');
MyNamespace.myFunction();
Important Notes:
-
Use
export
keyword to expose interfaces, classes, functions, etc., outside the namespace. -
Namespaces can be split across multiple files, but you need to use
/// /// <reference path="path/to/namespaceFile.ts" />
to reference files that contribute to the same namespace. -
For modern TypeScript projects, consider using ES6 modules (
import
andexport
) instead of namespaces, as namespaces can sometimes lead to complexity and potential issues with module systems.
Namespaces are handy for organizing code, but as TypeScript evolves, module-based approaches are generally preferred due to better maintainability, scalability, and compatibility with modern JavaScript module systems.