0
0
Typescriptprogramming~5 mins

Parameter type annotations in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Parameter type annotations
O(n)
Understanding Time Complexity

Let's see how adding type annotations to function parameters affects the time it takes for the program to run.

We want to know if specifying types changes how long the code takes as input grows.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


function sumArray(numbers: number[]): number {
  let total = 0;
  for (const num of numbers) {
    total += num;
  }
  return total;
}

This function adds up all numbers in an array, with a type annotation on the parameter.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through each number in the array.
  • How many times: Once for every item in the input array.
How Execution Grows With Input

As the array gets bigger, the function does more additions, one per item.

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

Pattern observation: The work grows directly with the number of items.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line with the input size.

Common Mistake

[X] Wrong: "Adding type annotations makes the code slower because it adds extra work at runtime."

[OK] Correct: Type annotations are only for the developer and compiler; they do not affect how many steps the program takes when running.

Interview Connect

Understanding that type annotations help catch errors early but don't slow down your code shows you know the difference between coding tools and program speed.

Self-Check

"What if we changed the function to call itself recursively instead of using a loop? How would the time complexity change?"