TypeScript Course
TypeScript
/
Beginner

ES Modules in TypeScript

Definition

The official standard format to package JavaScript code for reuse. TypeScript relies heavily on ES Modules (`import` and `export`) to share types, interfaces, and logic across files.

Explain Like I'm New

Before ES Modules, all JS files were just dumped into a giant global bucket, causing variables to overwrite each other. ES Modules give every file its own private room. Nothing leaves the room unless you explicitly `export` it, and nothing enters the room unless you explicitly `import` it.

Real World Example

Creating a `types.ts` file that holds all your global interfaces, and importing them into your React components to keep the component files clean.

Common Use Cases

  • •File separation
  • •Code reusability
  • •Avoiding global namespace pollution

Interactive Example

// file: models.ts
export interface User {
  id: number;
  name: string;
}
// Default export (Only one per file!)
export default function getAdmin() { return 'Admin'; }

// file: app.ts
// Named imports use { }, default imports don't.
import getAdmin, { User } from './models';

// TYPE-ONLY IMPORT (Best Practice for performance!)
import type { User as UserType } from './models';

const newUser: UserType = { id: 1, name: "Alice" };

Interview Questions

basic

  • What keywords are used to share code between files?

intermediate

  • Does exporting an `interface` add any code to your final JavaScript bundle?

advanced

  • What is `import type`?

Flash Cards

Question

Does exporting an interface add code?

Click to reveal answer
Answer

No. Because interfaces only exist at compile time, exporting and importing them leaves absolutely zero footprint in the compiled JavaScript bundle.

Question

What is import type?

Click to reveal answer
Answer

A TS-specific feature: `import type { User } from './types'`. It explicitly tells the compiler 'I am ONLY importing types, not real JS values'. This allows modern bundlers (like Vite or Webpack) to safely drop the import statement entirely during compilation, resulting in faster builds.