Typescript Foundations / Working with Modules

Default vs named exports

βœ… Named Exports

You explicitly name what you're exporting. You can export multiple values per file.

πŸ”Έ Syntax:

// math.ts
export const PI = 3.14;
export function add(a: number, b: number): number {
  return a + b;
}

πŸ”Έ Importing:

import { PI, add } from './math';

βœ… Pros:

  • Encourages clarity (you see exactly what you're importing).

  • Allows importing multiple items from the same file.

  • IDE auto-completion and type-checking are better.


βœ… Default Export

You export one main value from a module.

πŸ”Έ Syntax:

// config.ts
const API_URL = "<https://api.example.com>";
export default API_URL;

πŸ”Έ Importing:

import API_URL from './config';

You can rename the default import to anything during import.


βš–οΈ Key Differences

Feature

Named Export

Default Export

Syntax

export { item }

export default item

How many per file?

Many

Only one

Import syntax

import { item }

import item

Can you rename?

Yes, with as

Yes, without as

Auto-import in IDEs

More accurate

Sometimes less predictable


πŸ” Example Comparing Both

// utils.ts
export const greet = (name: string) => `Hello, ${name}`;
export default function log(message: string) {
  console.log(message);
}
// main.ts
import log, { greet } from './utils';

log(greet("Codeveda"));  // Output: Hello, Codeveda

πŸ” When to Use Which?

Use Case

Prefer This Export

Utility functions

Named

Only one main functionality

Default

Shared constants/types

Named

Library modules (e.g., React)

Default (often)