Modules let you organise code into separate files. Each file is a module
that can export values, types, and functions for other files to import.
TypeScript follows the same import/export syntax as modern
JavaScript (ES Modules).
Named Exports
Export multiple values by name:
TypeScript
// utils.ts
export function slugify(text: string): string {
return text.toLowerCase().replace(/\s+/g, "-");
}
export function capitalize(text: string): string {
return text.charAt(0).toUpperCase() + text.slice(1);
}
export interface Config {
apiUrl: string;
timeout: number;
}TypeScript
// app.ts
import { slugify, capitalize, type Config } from "./utils";
const config: Config = { apiUrl: "https://api.example.com", timeout: 5000 };
console.log(slugify("Hello World")); // "hello-world"
console.log(capitalize("hello")); // "Hello"Default Exports
Each module can have one default export — the main thing it exports:
TypeScript
// Logger.ts
export default class Logger {
private prefix: string;
constructor(prefix: string) {
this.prefix = prefix;
}
log(msg: string): void {
console.log(`[${this.prefix}] ${msg}`);
}
}TypeScript
// app.ts
import Logger from "./Logger"; // no braces for default export
const logger = new Logger("APP");
logger.log("Started");Re-exporting (Barrel Files)
Create an index.ts that re-exports from multiple modules:
TypeScript
// index.ts — barrel file
export { slugify, capitalize } from "./utils";
export type { Config } from "./utils";
export { default as Logger } from "./Logger";TypeScript
// app.ts — clean imports from one place
import { slugify, Logger } from "./utils";Type-Only Imports
When you only need the type (erased at compile time):
TypeScript
import type { Config } from "./utils";This prevents circular dependencies and keeps the compiled output clean.
Namespace Imports
Import everything under a single name:
TypeScript
import * as utils from "./utils";
utils.slugify("Hello");
utils.capitalize("world");Module Resolution
TypeScript resolves modules in this order:
- Relative paths (
./utils,../lib/helper) node_modulespackages (react,lodash)- Path aliases configured in
tsconfig.json
JSON
{
"compilerOptions": {
"paths": {
"@/*": ["./src/*"]
}
}
}Then:
TypeScript
import { User } from "@/models/user";Tips
- One module, one responsibility — each file should do one thing.
- Use named exports for libraries, default exports for components and classes.
- Always use
import typewhen importing only types. - Avoid circular dependencies — if A imports B and B imports A, restructure.
Next: unions & intersections — composing types.