TypeScript
/Beginner
Import & Export Syntax
Definition
The precise syntax used to expose and consume modules in TypeScript, including named exports, default exports, and re-exporting.
Explain Like I'm New
Named exports are like a grocery store aisle: you pick exactly which specific items you want from the shelf using `{ }`. Default exports are like a subscription box: the file hands you one main item, and you can name the box whatever you want when you receive it.
Real World Example
A `utils.ts` file exports 10 different helper functions using named exports. In `app.ts`, you only `import { formatDate }` so you don't load the other 9 into memory.
Common Use Cases
- •Tree-shaking (removing unused code)
- •Structuring large applications
Interactive Example
// file: math.ts export const PI = 3.14; export function add(a: number, b: number) { return a + b; } export default class Calculator { } // file: index.ts (Barrel File) export * from './math'; // Re-exports everything except defaults export { default as Calc } from './math'; // Re-exporting a default with a new name
Interview Questions
basic
- What is the difference between Named and Default exports?
intermediate
- Can a file have both a default export and named exports?
advanced
- What is a Barrel File (`export * from`)?