TypeScript Course
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`)?

Flash Cards

Question

Can a file have both?

Click to reveal answer
Answer

Yes. A file can have an infinite number of Named exports, and exactly ONE Default export.

Question

What is a Barrel File?

Click to reveal answer
Answer

An `index.ts` file that imports from many files in a folder and immediately re-exports them. It allows consumers to import from the folder directly `import { User, Post } from './models'` instead of `import { User } from './models/user'; import { Post } from './models/post';`.