Array type annotation syntax in Typescript - Time & Space Complexity
When we write code with arrays, we often tell TypeScript what kind of items the array holds. This is called array type annotation.
We want to understand how the time to check or use these annotations grows as the array size grows.
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 sums all numbers in an array annotated as number[].
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each element of the array.
- How many times: Once for every item in the array.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The number of operations grows directly with the number of items.
Time Complexity: O(n)
This means the time to sum the array grows in a straight line as the array gets bigger.
[X] Wrong: "Type annotations slow down the program as the array grows because they add extra work at runtime."
[OK] Correct: Type annotations are only for the developer and compiler; they do not affect how fast the program runs when it is running.
Understanding how array operations scale helps you write clear and efficient code. Knowing that type annotations do not add runtime cost shows your grasp of TypeScript's design.
"What if we changed the array type from number[] to (number | string)[]? How would the time complexity change?"