TypeScript Function Overloads (original) (raw)
Last Updated : 23 Jan, 2025
TypeScript function overloads enable defining multiple signatures for a single function, allowing it to handle various parameter types or counts.
- Enhances type safety by ensuring correct argument handling.
- Improves code flexibility and readability. JavaScript ``
function greet(person: string): string;
function greet(person: string, age: number): string;
function greet(person: string, age?: number): string {
if (age !== undefined) {
return Hello, <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mrow><mi>p</mi><mi>e</mi><mi>r</mi><mi>s</mi><mi>o</mi><mi>n</mi></mrow><mo stretchy="false">!</mo><mi>Y</mi><mi>o</mi><mi>u</mi><mi>a</mi><mi>r</mi><mi>e</mi></mrow><annotation encoding="application/x-tex">{person}! You are </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.8889em;vertical-align:-0.1944em;"></span><span class="mord"><span class="mord mathnormal">p</span><span class="mord mathnormal">erso</span><span class="mord mathnormal">n</span></span><span class="mclose">!</span><span class="mord mathnormal" style="margin-right:0.22222em;">Y</span><span class="mord mathnormal">o</span><span class="mord mathnormal">u</span><span class="mord mathnormal">a</span><span class="mord mathnormal">re</span></span></span></span>{age} years old.
;
}
return Hello, ${person}!
;
}
console.log(greet("Alice")); console.log(greet("Bob", 30));
``
- The function greet has two overloads: one with a single parameter person and another with person and age.
- The implementation checks if age is provided and returns an appropriate greeting.
**Output:
Hello, Alice!
Hello, Bob! You are 30 years old.
More Example of TypeScript function Overloads
Adding Numbers or Concatenating Strings
JavaScript `
function combine(a: number, b: number): number; function combine(a: string, b: string): string; function combine(a: any, b: any): any { return a + b; }
console.log(combine(5, 10));
console.log(combine("Hello, ", "World!"));
`
- The combine function is overloaded to handle both numbers and strings, either adding or concatenating them.
- The implementation uses a single function to manage both scenarios.
**Output:
15
Hello, World!
**Fetching Data by ID or Query
JavaScript ``
function fetchData(id: number): string;
function fetchData(query: string): string[];
function fetchData(param: any): any {
if (typeof param === 'number') {
return Data for ID: ${param}
;
} else {
return [Result for query: ${param}
];
}
}
console.log(fetchData(42));
console.log(fetchData("search term"));
``
- The fetchData function is overloaded to accept either a numeric ID or a string query.
- It returns a string for an ID and an array of strings for a query.
**Output:
Data for ID: 42
Result for query: search term
Calculating Area for Different Shapes
JavaScript `
function calculateArea(radius: number): number; function calculateArea(length: number, width: number): number; function calculateArea(...args: number[]): number { if (args.length === 1) { return Math.PI * args[0] ** 2; } else { return args[0] * args[1]; } }
console.log(calculateArea(5));
console.log(calculateArea(10, 20));
`
- The calculateArea function is overloaded to compute the area of a circle when given one argument and a rectangle when given two arguments.
- It uses rest parameters to handle a varying number of arguments.
Output:
78.53981633974483
200
Best Practices for Using TypeScript Function Overloads
- **Define Clear and Specific Overloads: Ensure each overload signature is precise and unambiguous to enhance code readability and maintainability.
- **Order Overloads from Most Specific to Least Specific: Arrange overloads so that more specific signatures appear before more general ones, aiding the TypeScript compiler in selecting the correct overload.
- **Implement a Generalized Function Body: The function implementation should accommodate all defined overloads, using type guards or conditional logic to handle different parameter types appropriately.