Master TypeScript From Scratch

Learn TypeScript step by step with practical examples, interactive coding lessons, and real-world projects.

TypeScript Modules

Learn how to organize TypeScript code into separate files and share functions, classes, interfaces and types using import and export.

Simple Explanation: Modules divide an application into smaller, manageable files. We use export to make declarations available to other modules and import to use those declarations in another file.

1. What are Modules?

A TypeScript module is a file that can import declarations from other modules and export selected declarations for reuse. Modules help keep application code organized and maintainable.

For example, a student management application can keep student-related functions in one file, validation functions in another file and the main application logic in a separate file.

Example: Creating a Module

File: mathUtils.ts

export function add(a: number, b: number): number {
    return a + b;
}

File: app.ts

import { add } from "./mathUtils";

const result = add(10, 20);

console.log(result);

Expected Output

30

The add function is exported from mathUtils.ts and imported into app.ts. The application can then call the function using its imported name.

2. Modules Workflow Diagram

Understand how one TypeScript file shares its functionality with another file.

📄
Module A

Defines functions, classes or other declarations.

→
📤
Export

Makes selected declarations available to other modules.

→
📥
Import

Imports the required declarations into another file.

→
✅
Use Functionality

Calls the imported function or uses the imported type.

Remember: Other modules can import declarations that are exported. Each module can control which declarations it exposes.

3. Named Exports

Named exports allow a module to export multiple declarations. These declarations are imported using their exported names inside curly braces.

Example

File: studentUtils.ts

export const collegeName: string = "ABC College";

export function displayStudent(name: string): void {
    console.log("Student: " + name);
}

export function getAge(): number {
    return 22;
}

File: app.ts

import {
    collegeName,
    displayStudent,
    getAge
} from "./studentUtils";

console.log(collegeName);
displayStudent("Rahul");
console.log(getAge());

Expected Output

ABC College
Student: Rahul
22

Named imports use the exported names. You can import only the declarations that your module needs.

4. Default Exports

A module can have one default export. The importing module can choose its own local name for the default export and does not need curly braces.

Example

File: calculator.ts

export default function multiply(
    a: number,
    b: number
): number {
    return a * b;
}

File: app.ts

import multiply from "./calculator";

console.log(multiply(5, 4));

Expected Output

20

Named Export vs Default Export

Feature Named Export Default Export
Syntax export function add() { ... } export default function add() { ... }
Import syntax import { add } from "./file" import add from "./file"
Import name Matches the exported name unless renamed. Can use a different local name.
Count per module Multiple named exports are allowed. At most one default export is allowed.

5. Import Aliases

Import aliases let you use a different local name for an imported declaration. They are useful when different modules export declarations with the same name.

Example

File: student.ts

export function display(): void {
    console.log("Student module");
}

File: teacher.ts

export function display(): void {
    console.log("Teacher module");
}

File: app.ts

import { display as displayStudent } from "./student";
import { display as displayTeacher } from "./teacher";

displayStudent();
displayTeacher();

Expected Output

Student module
Teacher module

Both files export a function named display, but the imports use different local names to avoid a naming conflict.

6. Exporting Interfaces and Types

Interfaces and type aliases can also be exported and imported. This allows multiple modules to share consistent type definitions.

Example

File: models.ts

export interface Student {
    id: number;
    name: string;
}

export type CourseName = string;

File: app.ts

import type { Student, CourseName } from "./models";

const student1: Student = {
    id: 101,
    name: "Priya"
};

const course: CourseName = "TypeScript";

console.log(student1.name);
console.log(course);

Expected Output

Priya
TypeScript
Remember: import type makes it explicit that the imported declarations are used as types. Interfaces and type aliases are erased from emitted JavaScript.

7. Re-exporting from Another Module

A module can re-export declarations from other modules. This lets us create a central entry point that exposes related functions from multiple files.

Example

File: math/add.ts

export function add(a: number, b: number): number {
    return a + b;
}

File: math/multiply.ts

export function multiply(a: number, b: number): number {
    return a * b;
}

File: math/index.ts

export { add } from "./add";
export { multiply } from "./multiply";

File: app.ts

import { add, multiply } from "./math";

console.log(add(10, 5));
console.log(multiply(10, 5));

Expected Output

15
50

The math/index.ts file acts as a central entry point. The exact import path resolution depends on your TypeScript and runtime configuration.

8. Module Scope

When a file contains a top-level import or export, it is treated as a module. Declarations inside a module are scoped to that module unless they are explicitly exported.

Example

File: studentService.ts

const schoolName = "ABC School";

export function getSchoolName(): string {
    return schoolName;
}

File: app.ts

import { getSchoolName } from "./studentService";

console.log(getSchoolName());

// schoolName is not directly imported or exported.

Expected Output

ABC School

The schoolName variable remains internal to studentService.ts. Other modules can call the exported function without importing that variable.

9. Example Module Folder Structure

A project can organize related modules into folders to make the application easier to navigate and maintain.

src/
├── app.ts
├── models/
│   └── student.ts
├── utilities/
│   ├── mathUtils.ts
│   └── stringUtils.ts
└── services/
    └── studentService.ts

Module Organization Diagram

📋
Models

Contains interfaces and type definitions.

🛠️
Utilities

Contains reusable helper functions.

⚙️
Services

Contains application-related operations.

Each module can export the declarations it needs to share. The app.ts file can import the required functionality and coordinate the application.

10. Important Rules of Modules

Rule Explanation
Named export Import by the exported name using curly braces.
Default export Import without curly braces, choosing a local name.
Import alias Use as to rename an imported declaration locally.
Type-only import Use import type for declarations used as types.
Relative path A path such as ./mathUtils refers to a module relative to the current file.
Re-export Share a declaration through another module.
Configuration Module resolution and emitted JavaScript depend on the project configuration.

Summary

TypeScript modules organize code into separate files. Named exports share multiple declarations, default exports provide a module's default declaration, import aliases allow local renaming, type-only imports share types, and re-exporting creates central entry points. Module scope also prevents internal declarations from becoming directly accessible to other modules.

Next, learn Namespaces and how to group related TypeScript declarations under a named scope.