Explicit type annotations in Typescript - Time & Space Complexity
We want to see how adding explicit type annotations affects the speed of running TypeScript code.
Does writing types change how fast the program runs?
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;
}
const data = [1, 2, 3, 4, 5];
console.log(sumArray(data));
This code adds up all numbers in an array using explicit type annotations for the function and its 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 array.
As the array gets bigger, the program does more additions, one for each number.
| 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 as the input size grows.
[X] Wrong: "Adding explicit type annotations makes the program slower at running."
[OK] Correct: Type annotations help during coding but are removed when running, so they do not affect speed.
Understanding that type annotations help with code clarity but do not slow down the program shows you know how TypeScript works behind the scenes.
"What if we removed the explicit return type from the function? How would the time complexity change?"