Why type annotations are needed in Typescript - Performance Analysis
We want to see how adding type annotations affects the time it takes for TypeScript to check code.
How does the presence of type annotations change the work the compiler does?
Analyze the time complexity of this TypeScript code with type annotations.
function sum(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 explicit type annotations on parameters and return.
Look at what repeats when the code runs or is checked.
- Primary operation: Looping through each number in the array.
- How many times: Once for each element in the input array.
As the array gets bigger, the work grows in a simple way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 additions and checks |
| 100 | About 100 additions and checks |
| 1000 | About 1000 additions and checks |
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 program run slower."
[OK] Correct: Type annotations help the compiler check code but do not slow down the running program itself.
Understanding how type annotations affect compile-time work helps you write clear code and explain your choices confidently.
"What if we removed the type annotations? How would the time complexity of type checking change?"