Function overloads in Typescript - Time & Space Complexity
We want to see how the time a function takes changes when it has multiple ways to be called, called overloads.
Does having many overloads make the function slower as input grows?
Analyze the time complexity of the following code snippet.
function combine(a: number, b: number): number;
function combine(a: string, b: string): string;
function combine(a: any, b: any): any {
return a + b;
}
const result1 = combine(1, 2);
const result2 = combine('hello', 'world');
This code shows a function with two overloads: one for numbers and one for strings, both adding the inputs.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The function runs a simple addition operation once per call.
- How many times: Each call executes the addition exactly one time, no loops or recursion.
Each call does one addition, so the time grows directly with how many times you call the function.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The time grows straight with the number of calls, not with the number of overloads.
Time Complexity: O(n)
This means the time grows directly with how many times you call the function, regardless of overloads.
[X] Wrong: "More overloads make the function slower for each call."
[OK] Correct: Overloads only affect how the function is called, not the speed of each call, which stays simple.
Understanding how overloads affect performance helps you explain your code clearly and shows you know how function calls work under the hood.
"What if the function body had a loop inside? How would the time complexity change?"