TypeScript ยท Chapter 27 of 44

TypeScript Modules

Modules let you split your code across multiple files, exporting the pieces you want to share and importing them where needed. This keeps large codebases organized and manageable.

TypeScript uses the same `export` and `import` syntax as modern JavaScript (ES modules), so anything you already know about ES modules applies directly to TypeScript files.

Syntax
// math.ts
export function add(a: number, b: number): number {
  return a + b;
}

// app.ts
import { add } from "./math";

Exporting

You can export individual items with `export` in front of a declaration, such as `export function add() {}`, or export a single default item per file with `export default`.

Importing

You bring exported items into another file with `import { add } from "./math";` for named exports, or `import add from "./math";` for a default export.

Example 1 (typescript)
// math.ts
export function add(a: number, b: number): number {
  return a + b;
}
Output
(no direct output โ€” a module file)

The add function is exported so other files can import and use it.

Example 2 (typescript)
// app.ts
import { add } from "./math";
console.log(add(2, 3));
Output
5

app.ts imports the named export add from math.ts and calls it.

Key points

  • Modules split code across multiple files.
  • `export` shares a value, function, class, or type from a file.
  • `import` brings exported items into another file.
  • TypeScript uses standard ES module import/export syntax.
๐Ÿ’ก Note: Each file with a top-level import or export is treated as its own module scope.

๐Ÿ“ Quick Quiz

1. What keyword shares a value from a file?

2. How do you import a named export called add from './math'?

3. Why use modules?