#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

  1. Create utils.ts exporting a function capitalize.
  2. Create types.ts exporting an interface Config.
  3. Import both in main.ts and use them.

See you on Day 26 for Declaration Files!