Modules in TypeScript
Modules help you split your code into smaller, reusable parts, making it easier to manage. Each module can export variables, functions, or classes to be used in other files.
Exporting from a Module
Named Exports
You can export multiple things from a module:
export const add = (a: number, b: number) => a + b;export const subtract = (a: number, b: number) => a - b;Importing named exports:
import { add, subtract } from './math';
console.log(add(5, 3)); // 8console.log(subtract(10, 4)); // 6Default Exports
A module can have one default export:
export default (name: string) => `Hello, ${name}!`;Importing a default export:
import greet from './greet';
console.log(greet('TypeScript')); // Hello, TypeScript!Importing Everything
You can import everything from a module as an object:
import * as Math from './math';
console.log(Math.add(2, 3)); // 5Key Points :
- Named exports allow exporting multiple things.
- Default exports export one value per module.
- Use
import *to import all exports as an object.
💡 Conclusion
Modules help keep your code organized and reusable. Use them to split logic into smaller parts and import what you need!