You are viewing a free preview of this lesson.
Subscribe to unlock all 12 lessons in this course and every other course on LearningBro.
As TypeScript applications grow, organising code into modules becomes essential. TypeScript fully supports ECMAScript modules (ESM) and adds features such as type-only imports and ambient module declarations. This lesson covers the module system, namespaces (and why they are largely historical), and declaration files.
TypeScript uses the standard ES module syntax. Any file containing a top-level import or export is treated as a module:
// utils.ts
export function formatDate(date: Date): string {
return date.toISOString().split('T')[0];
}
export const MAX_RETRIES = 3;
export interface Logger {
log(message: string): void;
error(message: string): void;
}
// app.ts
import { formatDate, MAX_RETRIES, Logger } from './utils';
import type { Logger } from './utils'; // type-only import (see below)
console.log(formatDate(new Date()));
A module can have one default export:
// database.ts
export default class Database {
constructor(private connectionString: string) {}
connect(): void {
console.log(`Connecting to ${this.connectionString}`);
}
}
// app.ts
import Database from './database';
const db = new Database('postgres://localhost:5432/mydb');
You can re-export from other modules to create barrel files:
Subscribe to continue reading
Get full access to this lesson and all 12 lessons in this course.