TypeScript's export and import features are essential for creating modular, maintainable code. These mechanisms allow developers to share functionality between different parts of their applications efficiently.
The export
keyword is used to make functions, classes, or variables available for use in other modules. There are two main ways to export:
Named exports allow you to export multiple items from a single module:
// math.ts
export const PI = 3.14159;
export function add(a: number, b: number): number {
return a + b;
}
Default exports are used when you want to export a single main item from a module:
// greeting.ts
export default function sayHello(name: string): string {
return `Hello, ${name}!`;
}
The import
statement is used to bring exported items into another module. There are several ways to import:
To import specific named exports:
import { PI, add } from './math';
console.log(PI); // 3.14159
console.log(add(2, 3)); // 5
To import a default export:
import sayHello from './greeting';
console.log(sayHello('Alice')); // Hello, Alice!
To import all exports as a namespace:
import * as MathUtils from './math';
console.log(MathUtils.PI);
console.log(MathUtils.add(2, 3));
index.ts
) to simplify imports in large projectsTo deepen your understanding of TypeScript modules, explore these related topics:
By mastering export and import in TypeScript, you'll be able to create more modular and maintainable code, improving your overall development experience with TypeScript vs JavaScript.