A namespace in TypeScript is a way to organize and group related code, especially when you want to avoid naming conflicts. It allows you to encapsulate variables, interfaces, classes, functions, etc., under a single name. This is especially useful when writing large applications where you need to structure your code logically.
- Namespace Declaration: You declare a namespace using the
namespace
keyword, and everything inside it is scoped to that namespace. - Exporting: You can export members of the namespace using the
export
keyword so they can be used outside the namespace. - Accessing Members: To access the members of a namespace, you use the namespace name followed by a dot (
.
), likeValidation.StringValidator
.
Example:
namespace MyNamespace {
export class MyClass {
// class code
}
}
Multi-file Namespaces
In larger applications, you might want to split your namespaces across multiple files. To do this:
- Reference other files using the
/// <reference path="..." />
directive. - Declare a namespace in each file and extend or modify it as needed.
Example Breakdown:
- Validation namespace: Contains interfaces and classes that perform validation, like
StringValidator
and the classes that implement it (LettersOnlyValidator
,ZipCodeValidator
). - Multi-file Setup:
Validation.ts
contains the base interface.LettersOnlyValidator.ts
contains the logic for a specific validator.Test.ts
uses all the above files and tests the validators.
This approach helps organize code, especially when working with large projects where code is split into many files but logically belongs together.