Typescript module
Created By: chatGPT
TypeScript modules are a way to organize and encapsulate code in a more manageable manner. They help in dividing your code into separate files and namespaces, promoting better maintainability and code reusability. A module can export variables, functions, classes, or interfaces that can be imported into other modules.
export class User {
constructor(public name: string, public age: number) {}
greet() {
return `Hello, my name is ${this.name} and I'm ${this.age} years old.`;
}
}
To create a module in TypeScript, you can define your components in a
.ts
file and use the export
keyword to make them accessible. In another file, you can import these components using the import
statement.import { User } from './User';
const user1 = new User('Alice', 30);
console.log(user1.greet());
You can also create default exports in TypeScript. A default export allows you to export a single class, function, or primitive value from a module without the need for braces when importing. This can simplify the import syntax for commonly used modules.
export default class Product {
constructor(public title: string, public price: number) {}
}
To import a default export, the syntax will slightly change. You won't use curly braces when importing the default export from a module.
import Product from './Product';
const prod1 = new Product('Coffee', 5);
console.log(prod1);
Namespace is another feature in TypeScript that allows you to group related functionality together. Although modern builds typically use modules, namespaces can still be useful in certain scenarios. You can define a namespace using the
namespace
keyword.namespace Utilities {
export function log(message: string) {
console.log(message);
}
}
To use a function from a namespace, you will prefix your calls with the namespace name. This clarifies which part of your code is being referenced and reduces naming conflicts.
Utilities.log('This is a message from the Utilities namespace.');