TypeScript by Example: Modules
Organizing TypeScript code with ES6 module imports and exports in this practical sample code. Demonstrates export interface, export const, export class, and named import syntax for creating modular, maintainable applications with explicit dependency management.
Code
// validation.ts
export interface StringValidator {
isAcceptable(s: string): boolean;
}
export const numberRegexp = /^[0-9]+$/;
export class ZipCodeValidator implements StringValidator {
isAcceptable(s: string) {
return s.length === 5 && numberRegexp.test(s);
}
}
// main.ts
// import { ZipCodeValidator } from "./validation";
// let myValidator = new ZipCodeValidator();
// console.log(myValidator.isAcceptable("12345")); // trueExplanation
TypeScript modules follow the ES6 standard where each file with imports or exports becomes a module with its own scope. Unlike older JavaScript where everything lived in the global scope, modules keep their variables and functions private unless explicitly exported. This prevents naming conflicts and makes dependencies explicit—you can see exactly what each file uses from other files.
Use export to share code from a module and import to bring in code from other modules. TypeScript supports named exports for multiple exports per file (imported with curly braces) and default exports for the main export of a module (imported without braces).
The module system provides several benefits:
- Automatic dependency management avoids global namespace pollution
- Tree-shaking eliminates unused code from production bundles
- Explicit imports make code dependencies immediately visible
- Better code organization for large-scale applications
Code Breakdown
export interface makes the interface available in other files.export const shares a constant across modules.export class allows the class to be imported elsewhere.import { ZipCodeValidator } uses named import syntax.
