1. Welcome and Icebreaker:
- If you could give a function multiple personalities, what would they be?
2. Outline the Session:
- We’ll learn about function overloading in TypeScript: what it is, how to declare overloads, and why it’s useful.
- Learning Outcomes: Understand how to provide multiple signatures for a function and handle different argument types.
- Ask questions as we go!
3. Concept Explanation:
- Function Overloading allows a function to have multiple signatures. This means you can call the same function with different argument types or counts, and TypeScript will enforce the correct usage.
- Syntax:
- Declare multiple function signatures (overloads) above the function implementation.
- The implementation must be compatible with all overloads.
- Use Cases:
- Functions that can accept different types or numbers of arguments (e.g., a function that can add numbers or concatenate strings).
- Note: Only one implementation is allowed, but you can have multiple overload signatures.
4. Live Coding Demonstration:
// Function overload signatures
declare function combine(a: number, b: number): number;
declare function combine(a: string, b: string): string;
// Implementation
function combine(a: any, b: any): any {
if (typeof a === "number" && typeof b === "number") {
return a + b;
}
if (typeof a === "string" && typeof b === "string") {
return a + b;
}
throw new Error("Invalid arguments");
}
console.log(combine(2, 3)); // 5
console.log(combine("Hello, ", "World!")); // Hello, World!
// console.log(combine(2, "test")); // Error at runtime
// Another example: function that can take a single string or an array of strings
function greet(name: string): string;
function greet(names: string[]): string[];
function greet(nameOrNames: string | string[]): string | string[] {
if (typeof nameOrNames === "string") {
return `Hello, ${nameOrNames}!`;
} else {
return nameOrNames.map(name => `Hello, ${name}!`);
}
}
console.log(greet("Alice")); // Hello, Alice!
console.log(greet(["Bob", "Charlie"])); // ["Hello, Bob!", "Hello, Charlie!"]
5. Tasks:
- Short Exercise:
- Write overloads for a function
reverse that takes either a string or an array of numbers and returns the reversed value.
- Implement the
reverse function to handle both cases.
- Test your function with both a string and an array of numbers.