1. Welcome and Icebreaker:
- If you could import any skill from someone else, what would it be?
2. Outline the Session:
- We’ll learn about import and export statements in TypeScript modules.
- Learning Outcomes: Understand how to use
import and export to share code between files.
- Let’s connect our code!
3. Concept Explanation:
- Exporting: Use
export to make variables, functions, classes, or interfaces available outside a module.
- Importing: Use
import to bring in exports from another module.
- Default Export: Each module can have one default export, imported without curly braces.
- Named Export: You can have multiple named exports, imported with curly braces.
- Syntax:
// Named export
export const value = 42;
import { value } from './module';
// Default export
export default function greet() { ... }
import greet from './module';
4. Live Coding Demonstration:
// math.ts
export function add(a: number, b: number): number {
return a + b;
}
export default function subtract(a: number, b: number): number {
return a - b;
}
// main.ts
import subtract, { add } from './math';
console.log(add(5, 3)); // 8
console.log(subtract(5, 3)); // 2
// Renaming imports/exports
export { add as sum };
import { sum } from './math';
5. Tasks:
- Short Exercise:
- Create a module with both a default export and a named export.
- Import both into another file and use them.
- Try renaming an import using
as.
- Practice exporting and importing interfaces.