TypeScript Tutorial

Modules

Organizing TypeScript code using ES6 import/export syntax

What are Modules?

In TypeScript, code is organized into Modules. A module is a file that contains its own scope. Variables, functions, and classes defined in a module are not visible outside the file unless you explicitly export them.
typescript
// math.ts
export const PI = 3.14;

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

Importing Code

To use code from another module, you use the import keyword.
typescript
// main.ts
import { PI, add } from "./math";

console.log(add(PI, 10));

Default Exports

Each module can have at most one default export. This is often used for the main class or function in a file.
typescript
// Logger.ts
export default class Logger {
    log(msg: string) { console.log(msg); }
}

// main.ts
import MyLogger from "./Logger"; // You can name it anything!

Namespaced Imports

If a module exports many things, you can import everything at once under a single name using the * as syntax.
typescript
import * as MathUtils from "./math";
console.log(MathUtils.PI);

Type-Only Imports

Wait! TypeScript allows you to import ONLY types. This is a great optimization because it ensures the import is completely removed when the code is converted to JavaScript.
typescript
import type { User } from "./types";

Summary

TermSyntaxDescription
exportexport const xMake a value available
importimport { x }Bring a value into scope
defaultexport default xThe "main" export of a file
asimport { x as y }Renaming an import
import typeimport type { T }Optimized type-only import
Best ForOrganizing large apps, reusable libraries
LogicOne file = One module
SafetyPrevents global namespace pollution
ModernTS uses standard ES6 module syntax
StandardEstablished and trusted worldwide for 10+ years
RefactorSplitting large files into small, focused modules
Dynamicimport("./mod").then(...) (Lazy loading code!)
Declarationmodule.d.ts (Defining modules for external JS libs)