Export and Import in TypeScript
Take your programming skills to the next level with interactive lessons and real-world projects.
Explore Coddy →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.
Exporting in TypeScript
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
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
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}!`;
}
Importing in TypeScript
The import statement is used to bring exported items into another module. There are several ways to import:
Named Imports
To import specific named exports:
import { PI, add } from './math';
console.log(PI); // 3.14159
console.log(add(2, 3)); // 5
Default Imports
To import a default export:
import sayHello from './greeting';
console.log(sayHello('Alice')); // Hello, Alice!
Namespace Imports
To import all exports as a namespace:
import * as MathUtils from './math';
console.log(MathUtils.PI);
console.log(MathUtils.add(2, 3));
Best Practices
- Use named exports for multiple related items
- Use default exports for the main functionality of a module
- Keep your exports consistent and well-organized
- Use descriptive names for your imports and exports
- Consider using barrel files (
index.ts) to simplify imports in large projects
Related Concepts
To 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.