Lab 07: Modules & Declarations

Objective

Use ES modules with TypeScript, write and consume .d.ts declaration files, augment existing modules, and organize code with barrels and namespaces.

Time

25 minutes

Prerequisites

  • Lab 04 (Classes)

Tools

  • Docker image: zchencow/innozverse-ts:latest


Lab Instructions

Step 1: ES Module Imports & Exports

// Named exports
export function add(a: number, b: number): number { return a + b; }
export const PI = 3.14159;
export type Point = { x: number; y: number };
export interface Shape { area(): number; }

// Default export
export default class Calculator {
    constructor(private value: number = 0) {}
    add(n: number): this { this.value += n; return this; }
    result(): number { return this.value; }
}

// Re-export
export { readFileSync as readFile } from "fs";
export * from "./utils";       // re-export all named exports
export * as utils from "./utils"; // namespace re-export

💡 import type (TypeScript 3.8+) is a type-only import that is completely erased at runtime — no require() or import() is emitted. Use it for interfaces, type aliases, and enums that are only needed for type checking. This speeds up compilation and prevents circular dependency issues.

📸 Verified Output:


Step 2: Declaration Files (.d.ts)

💡 .d.ts files are the glue between JavaScript and TypeScript. When you install @types/lodash, you get a .d.ts file describing lodash's types without changing lodash's source. The DefinitelyTyped project maintains 8,000+ such files. For your own JS, tsc --declaration generates .d.ts automatically.

📸 Verified Output:


Steps 3–8: Barrel Files, Namespaces, Path Aliases, Circular Deps, Tree Shaking, Capstone

💡 Namespaces are rarely needed in modern TypeScript — ES modules replaced their use case. The exception is declaration files (.d.ts) for global APIs like DOM and ambient declarations for window/global. In application code, use modules. In library type declarations, namespaces still make sense.

📸 Verified Output:


Summary

TypeScript modules are the backbone of large-scale applications. You've covered named/default exports, import type, declaration files, module augmentation, barrel files, namespaces, dynamic imports, path aliases, and a simple module registry system.

Further Reading

Last updated