Default and Named Exports

1. Welcome and Icebreaker:

  • If you could choose a default activity for your day, what would it be? What about a few named activities?

2. Outline the Session:

  • We’ll learn about default and named exports in TypeScript modules.
  • Learning Outcomes: Understand the difference between default and named exports, and when to use each.
  • Let’s export our knowledge!

3. Concept Explanation:

  • Default Export: Each module can have one default export. Imported without curly braces.
  • Named Export: Modules can have multiple named exports. Imported with curly braces.
  • When to Use:
    • Use default export for the main value/function/class of a module.
    • Use named exports for multiple exports from a module.
  • Syntax:
    // default export
    export default function main() { ... }
    // named export
    export function helper() { ... }
    // importing
    import main, { helper } from './module';
    

4. Live Coding Demonstration:

// logger.ts
export default function log(message: string) {
  console.log(message);
}
export function warn(message: string) {
  console.warn(message);
}

// app.ts
import log, { warn } from './logger';
log('Hello!');
warn('Be careful!');

5. Tasks:

  • Short Exercise:
    1. Create a module with a default export (a function) and two named exports (functions or variables).
    2. Import all exports into another file and use them.
    3. Try importing the default export with a different name.