TYPESCRIPT

TypeScript Module: Syntax, Usage, and Examples

A TypeScript module allows you to organize code into reusable, self-contained units. Modules help avoid variable conflicts, improve code maintainability, and make importing and exporting functionality easy across different files.

How to Use a Module in TypeScript

A module in TypeScript is a file containing reusable code. You define a module by exporting variables, functions, classes, or interfaces and then importing them in another file.

Exporting from a Module

You can export a module in TypeScript using export.

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

export const PI = 3.14;

Importing a Module

To use an exported function or variable, import it in another file using import.

// main.ts
import { add, PI } from "./mathUtils";

console.log(add(2, 3)); // Output: 5
console.log(PI); // Output: 3.14

Default Exports

Modules can also have a default export, allowing you to import it without specifying a name.

// logger.ts
export default function logMessage(message: string): void {
  console.log(`Log: ${message}`);
}

// app.ts
import logMessage from "./logger";

logMessage("Hello, TypeScript!"); // Output: Log: Hello, TypeScript!

When to Use a Module in TypeScript

Organizing Code

Modules help you split large codebases into smaller, reusable parts. This keeps related functions, classes, and constants together.

// shapes.ts
export class Circle {
  constructor(public radius: number) {}

  getArea(): number {
    return Math.PI * this.radius * this.radius;
  }
}

export class Square {
  constructor(public side: number) {}

  getArea(): number {
    return this.side * this.side;
  }
}

// main.ts
import { Circle, Square } from "./shapes";

const circle = new Circle(5);
console.log(circle.getArea()); // Output: 78.54

const square = new Square(4);
console.log(square.getArea()); // Output: 16

Avoiding Naming Conflicts

Modules prevent variable and function name conflicts by keeping them scoped to their respective files.

// userService.ts
export function getUser() {
  return { name: "Alice" };
}

// authService.ts
export function getUser() {
  return { username: "admin" };
}

// main.ts
import { getUser as getUserFromUserService } from "./userService";
import { getUser as getUserFromAuthService } from "./authService";

console.log(getUserFromUserService()); // Output: { name: 'Alice' }
console.log(getUserFromAuthService()); // Output: { username: 'admin' }

Creating Reusable Libraries

If you're building a shared utility library, modules allow you to create a set of reusable functions and types.

// utils.ts
export function capitalize(str: string): string {
  return str.charAt(0).toUpperCase() + str.slice(1);
}

// app.ts
import { capitalize } from "./utils";

console.log(capitalize("hello")); // Output: Hello

Examples of Modules in TypeScript

Declaring a Module

Sometimes, you may need to declare a module to extend an existing one or define an external module.

// customModule.d.ts
declare module "customModule" {
  export function greet(name: string): string;
}

// main.ts
import { greet } from "customModule";

console.log(greet("Alice")); // Output: Hello, Alice!

Handling "Cannot Find Module" Errors

If TypeScript cannot find a module, check the following:

  1. Ensure the module exists: Verify that the module file is in the correct path.
  2. Check your import path: Use relative paths if importing local files.
  3. Install missing dependencies: If the module is external, install it using npm install module-name.
  4. Configure tsconfig.json: Ensure moduleResolution is set to "node" if using Node.js.

Example tsconfig.json:

{
  "compilerOptions": {
    "moduleResolution": "node",
    "baseUrl": "./",
    "paths": {
      "*": ["node_modules/*"]
    }
  }
}

Fixing "Cannot Use Import Statement Outside a Module"

This error occurs when running TypeScript files without proper module support. Solutions:

  • Ensure package.json includes "type": "module".
  • Use CommonJS syntax (require) if using Node.js without ES modules.
  • Run the file with a bundler like Webpack or configure tsconfig.json to use "module": "CommonJS".

{
  "compilerOptions": {
    "module": "CommonJS"
  }
}

Exporting an Entire Module

Instead of exporting items individually, export everything using export *.

// math.ts
export const add = (a: number, b: number) => a + b;
export const subtract = (a: number, b: number) => a - b;

// index.ts
export * from "./math";

// app.ts
import { add, subtract } from "./index";

console.log(add(10, 5)); // Output: 15
console.log(subtract(10, 5)); // Output: 5

Using Module Aliases

To simplify import paths, set up module aliases in tsconfig.json.

{
  "compilerOptions": {
    "baseUrl": "./",
    "paths": {
      "@utils/*": ["src/utils/*"]
    }
  }
}

Then, import using the alias:

// app.ts
import { capitalize } from "@utils/formatters";

console.log(capitalize("typescript")); // Output: TypeScript

Module Augmentation

You can extend an existing module using module augmentation.

// myLib.d.ts
declare module "myLib" {
  export function greet(name: string): string;
}

// extendMyLib.ts
import "myLib";

declare module "myLib" {
  export function farewell(name: string): string;
}

export function farewell(name: string): string {
  return `Goodbye, ${name}!`;
}

// main.ts
import { greet, farewell } from "myLib";

console.log(greet("Alice")); // Output: Hello, Alice!
console.log(farewell("Bob")); // Output: Goodbye, Bob!

TypeScript modules help organize code, avoid naming conflicts, and enable code reuse. You can export individual items, use default exports, or export everything at once. If you encounter module errors, check your file paths, tsconfig.json, and package settings.

Learn TypeScript for Free
Start learning now
button icon
To advance beyond this tutorial and learn TypeScript by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.

You can code, too.

© 2025 Mimo GmbH