Type annotation on function parameters in Typescript - Time & Space Complexity
When we add type annotations to function parameters, we want to know if it changes how long the function takes to run.
Does specifying types affect the speed or steps the program takes?
Analyze the time complexity of the following code snippet.
function sumNumbers(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 type annotations on the parameter and return value.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each number in the array.
- How many times: Once for each item in the input array.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 additions |
| 100 | About 100 additions |
| 1000 | About 1000 additions |
Pattern observation: The number of steps 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 function slower because it adds extra work."
[OK] Correct: Type annotations are only for the developer and compiler; they do not add steps when the program runs.
Understanding that type annotations do not affect runtime helps you focus on what really matters: the code's logic and efficiency.
"What if the function used nested loops over the input array? How would the time complexity change?"