TypeScript Essentials
TypeScript Modules
TypeScript Modules
Section titled “TypeScript Modules”Modules help organize code into separate files with explicit dependencies.
Exporting
Section titled “Exporting”// Named exportsexport const PI = 3.14159;export function add(a: number, b: number): number { return a + b;}export class Calculator { // ...}
// Export at end of fileconst subtract = (a: number, b: number) => a - b;export { subtract };
// Export with renameexport { subtract as minus };Default Exports
Section titled “Default Exports”// Default exportexport default class User { constructor(public name: string) {}}
// Orclass User { constructor(public name: string) {}}export default User;Importing
Section titled “Importing”// Import named exportsimport { PI, add, Calculator } from "./math";
// Import with aliasimport { add as sum } from "./math";
// Import all as namespaceimport * as math from "./math";math.add(1, 2);
// Import defaultimport User from "./user";
// Import bothimport User, { Role } from "./user";Re-exporting
Section titled “Re-exporting”// Re-export from another moduleexport { User } from "./user";export { PI, add } from "./math";
// Re-export allexport * from "./utils";
// Re-export with renameexport { User as Person } from "./user";Type-Only Imports
Section titled “Type-Only Imports”// Import types only (removed at runtime)import type { User } from "./user";
// Mixed importsimport { createUser, type User } from "./user";Module Resolution
Section titled “Module Resolution”// tsconfig.json{ "compilerOptions": { "moduleResolution": "node", "baseUrl": "./src", "paths": { "@/*": ["./*"], "@utils/*": ["./utils/*"] } }}
// Usageimport { helper } from "@utils/helper";