#typescript
#modules
Day 25: Modules and Namespaces
Organizing Code
Welcome to Day 25! Code organization is key.
ES Modules
TypeScript supports modern ES Modules (import/export). This is the standard way to share code between files.
// math.ts
export function add(a: number, b: number) { return a + b; }
export const PI = 3.14;
// app.ts
import { add, PI } from "./math";
console.log(add(10, PI));
Default Exports
// logger.ts
export default function log(msg: string) { ... }
// app.ts
import log from "./logger";
Type-Only Imports
You can import only the type. This is erased during compilation, keeping your bundle smaller.
import type { User } from "./types";
Namespaces
Before Modules, we had Namespaces.
namespace Validation {
export const regex = /.../;
}
Advice: Avoid Namespaces in modern code. Use Modules. Namespaces are mostly for legacy code or specific heavy library structures.
Challenge for Today
- Create
utils.tsexporting a functioncapitalize. - Create
types.tsexporting an interfaceConfig. - Import both in
main.tsand use them.
See you on Day 26 for Declaration Files!