In Typescript, both modules and namespaces provide mechanisms for organizing code and avoiding naming conflicts, but they have some key differences.
It's important to note that the concept of namespaces is an older way of organizing code, and modern Typescript projects typically use modules.
Use import and export keywords to manage modules.
// profile.ts import { getFullName } from "./utility.ts"; console.log(getFullName("Alice", "Collin")); // Output: "Alice Collin"
// utility.ts export function getFullName(first_name: string, last_name: string): string { return first_name + " " + last_name; }
Modules introduce their scope. Each module has its scope, and the names defined in a module are not automatically visible outside of it.
Helps avoid global namespace pollution.
Modules are typically file-based. Each module is defined in a separate file, and you can use import and export statements to control which parts of a module are visible outside.
Modules in Typescript often use the ES6 module syntax (import and export statements).
Works well with modern Javascript module systems and bundlers like webpack.
// utility.ts export const message: string = "Module Example Through Import and Export"; export function showMessage(): void { console.log(message); }
Modules can have default exports using export default.
// NamespaceExample.ts export namespace NamespaceExample { export const variableName: string = "" }
/// <reference path="./NamespaceExample.ts" /> NamespaceExample.variableName;
Use the `namespace` keyword to define a namespace and the `///
Namespaces augment the global scope. All the names defined within a namespace are added to the global scope.
Can potentially lead to naming conflicts if not used carefully.
Namespaces can be defined across multiple files using the
// NamespaceExample.ts namespace NamespaceExample { export const message: string = "This is a Sample Namespace Example"; export function showMessage(): void { console.log(message); } }
Namespaces use the `namespace` keyword.
Namespaces provide a way to encapsulate code within a named container. preventing from avoiding naming collisions.
Namespaces were a way of organizing code before the introduction of ES6 modules. However, they are still supported in TypeScript for backward compatibility.
Namespaces allow us to avoid naming conflicts with other parts of our code or third-party libraries by providing a distinct namespace for our code.