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:
// index.ts (barrel file)
export { formatDate } from './utils';
export { default as Database } from './database';
export type { Logger } from './utils';
TypeScript 3.8 introduced import type and export type, which are erased during compilation and produce no runtime code:
import type { User, Role } from './types';
import { createUser } from './users';
export type { User, Role };
// type-only imports cannot be used as values:
// const u = new User(); // Error if User is only imported as a type
Type-only imports are beneficial for:
TypeScript supports dynamic import() for code splitting:
async function loadModule() {
const { formatDate } = await import('./utils');
console.log(formatDate(new Date()));
}
Dynamic imports return a Promise and are useful for lazy loading in front-end applications.
When using JavaScript libraries that do not include TypeScript types, you need declaration files (.d.ts):
Most popular JavaScript libraries have community-maintained type definitions:
// Install type definitions for lodash:
// npm install --save-dev @types/lodash
Subscribe to continue reading
Get full access to this lesson and all 12 lessons in this course.