Parameter type annotations in Typescript - Time & Space 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.
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 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.
As the array gets bigger, the function does more additions, one per item.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows directly with the number of items.
Time Complexity: O(n)
This means the time to run grows in a straight line with the input size.
[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.
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.
"What if we changed the function to call itself recursively instead of using a loop? How would the time complexity change?"