ES Modules in TypeScript
TypeScript uses ES modules (import/export) for code organization. Understand named exports, default exports, re-exports, type-only imports, and how TypeScript resolves module paths.
35 min•By Priygop Team•Last updated: Feb 2026
Module Patterns
Example
// Named exports
export interface User {
id: number;
name: string;
email: string;
}
export type UserRole = "admin" | "editor" | "viewer";
export function createUser(name: string, email: string): User {
return { id: Date.now(), name, email };
}
export const MAX_USERS = 1000;
// Default export (one per file)
export default class UserService {
private users: User[] = [];
add(user: User): void {
this.users.push(user);
}
findById(id: number): User | undefined {
return this.users.find(u => u.id === id);
}
}
// Importing
import UserService, { User, UserRole, createUser } from "./userService";
import type { User } from "./userService"; // Type-only import (erased at runtime)
// Rename imports
import { User as UserType } from "./userService";
// Import everything
import * as UserModule from "./userService";
const user: UserModule.User = UserModule.createUser("Alice", "a@test.com");
// Re-export (barrel file — index.ts)
export { User, UserRole, createUser } from "./userService";
export { Product, ProductCategory } from "./productService";
export { OrderService } from "./orderService";
// Consumers import from one place: import { User, Product } from "./models";
// Dynamic imports (code splitting)
async function loadEditor() {
const { Editor } = await import("./editor");
return new Editor();
}
// Type-only exports
export type { User, UserRole }; // Only exports the types, not values