Function overloads in TypeScript allow you to declare multiple versions of the same function with different parameter signatures. TypeScript uses the function signatures to determine the appropriate version based on the arguments passed to the function.
Example:
function greet(person: string): string; function greet(person: string, age: number): string; function greet(person: string, age?: number): string { if (age) { return `Hello, ${person}, you are ${age} years old!`; } return `Hello, ${person}!`; } console.log(greet('John')); // "Hello, John!" console.log(greet('John', 30)); // "Hello, John, you are 30 years old!"
In this example, the function greet
has two overload signatures: one takes just the name, the other also takes the age. TypeScript selects the appropriate version based on the passed arguments.