Type annotation on variables in Typescript - Time & Space Complexity
We look at how adding type annotations to variables affects the speed of a TypeScript program.
Does specifying types change how long the program takes to run?
Analyze the time complexity of the following code snippet.
let total: number = 0;
const numbers: number[] = [1, 2, 3, 4, 5];
for (let i = 0; i < numbers.length; i++) {
total += numbers[i];
}
console.log(total);
This code sums all numbers in an array using a variable with a type annotation.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that adds each number to total.
- How many times: Once for each item in the array.
As the array gets bigger, the loop runs more times, adding each number once.
| 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 finish grows in a straight line with the input size.
[X] Wrong: "Adding type annotations makes the program slower because it adds extra work."
[OK] Correct: Type annotations are used only during coding and checking, not when the program runs, so they do not slow down execution.
Understanding that type annotations help with code clarity but do not affect runtime speed shows you know how TypeScript works behind the scenes.
"What if we replaced the for-loop with a built-in array method like .reduce()? How would the time complexity change?"