Namespaces and Modules in TypeScript
In TypeScript, namespaces and modules are used to organize and manage large codebases, by breaking them up into smaller, manageable units.
Namespaces are a way to group related objects and functions into a single unit. They provide a way to avoid naming conflicts in large codebases by encapsulating related objects and functions under a single namespace name. Here's an example of how you could define a namespace in TypeScript:
namespace UserModule {
export interface User {
name: string;
age: number;
email: string;
}
export function getUser(userId: number): User {
// logic to get user data from a database
return {
name: "John Doe",
age: 30,
email: "johndoe@example.com"
};
}
}
UserModule
namespace encapsulates a User
interface and a getUser
function. The export
keyword is used to make the interface and function available outside of the namespace. To use the User
interface and the getUser
function in another part of your code, you would access them through the namespace, like this:let user = UserModule.getUser(1);
console.log(user.name);
export
and import
keywords to define and access exports, respectively. Here's an example of how you could define a module in TypeScript:// user.ts
export interface User {
name: string;
age: number;
email: string;
}
export function getUser(userId: number): User {
// logic to get user data from a database
return {
name: "John Doe",
age: 30,
email: "johndoe@example.com"
};
}
// main.ts
import { User, getUser } from "./user";
let user = getUser(1);
console.log(user.name);
In this example, the user.ts
file defines a module with a User
interface and a getUser
function. The export
keyword is used to make the interface and function available to other modules. The main.ts
file then imports the User
interface and the getUser
function from the user
module, using the import
keyword and the from
keyword.
Overall, namespaces and modules are both useful for organizing and managing large codebases, by encapsulating related objects and functions and providing a way to avoid naming conflicts. While namespaces use the namespace
keyword and the export
keyword, modules use the export
and import
keywords. Both can be used effectively in TypeScript to organize your code.
Leave a Comment