0
0
Typescriptprogramming~5 mins

Function overloads in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Function overloads
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

Each call does one addition, so the time grows directly with how many times you call the function.

Input Size (n)Approx. Operations
1010 additions
100100 additions
10001000 additions

Pattern observation: The time grows straight with the number of calls, not with the number of overloads.

Final Time Complexity

Time Complexity: O(n)

This means the time grows directly with how many times you call the function, regardless of overloads.

Common Mistake

[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.

Interview Connect

Understanding how overloads affect performance helps you explain your code clearly and shows you know how function calls work under the hood.

Self-Check

"What if the function body had a loop inside? How would the time complexity change?"