TypeScript
Beginner
1 min read
ES Modules: Import, Export, and Re-export
Example
// math.ts — named exports
export function add(a: number, b: number): number { return a + b; }
export function subtract(a: number, b: number): number { return a - b; }
export const PI = 3.14159265358979;
// types.ts — type-only exports
export type { User, Product };
interface User { id: number; name: string }
interface Product { id: number; price: number }
// logger.ts — default export
export default class Logger {
constructor(private prefix: string) {}
log(msg: string): void { console.log(`[${this.prefix}] ${msg}`); }
}
// index.ts — aggregating re-exports
export { add, subtract, PI } from "./math";
export type { User, Product } from "./types";
export { default as Logger } from "./logger";
// app.ts — consuming the module
import { add, PI } from "./math";
import type { User } from "./types"; // type-only, erased at runtime
import Logger from "./logger";
const logger = new Logger("App");
logger.log(`PI is approximately ${PI}`);
logger.log(`1 + 2 = ${add(1, 2)}`);
const user: User = { id: 1, name: "Alice" };
logger.log(`User: ${user.name}`);
// Inline type specifier (TS 4.5+)
import { type Product, add as addNumbers } from "./index";
Related Resources
TypeScript Reference
Complete tag & property list
TypeScript How-To Guides
Step-by-step practical guides
TypeScript Exercises
Practice what you've learned
More in TypeScript