Type erasure and its consequences in Typescript - Time & Space Complexity
When TypeScript code runs, its types disappear. This is called type erasure.
We want to see how this affects the speed of the program as it runs.
Analyze the time complexity of the following TypeScript function using generics.
function findFirst<T>(arr: T[], value: T): number {
for (let i = 0; i < arr.length; i++) {
if (arr[i] === value) {
return i;
}
}
return -1;
}
This function looks for the first place a value appears in an array.
Look for loops or repeated checks.
- Primary operation: The for-loop checking each item one by one.
- How many times: Up to the length of the array, n times in the worst case.
As the array gets bigger, the function checks more items.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Up to 10 checks |
| 100 | Up to 100 checks |
| 1000 | Up to 1000 checks |
Pattern observation: The number of checks grows directly with the size of the array.
Time Complexity: O(n)
This means the time to finish grows in a straight line as the input gets bigger.
[X] Wrong: "Because TypeScript uses types, the program runs faster or slower depending on types."
[OK] Correct: Types are removed before running, so they do not affect speed or how many steps the program takes.
Understanding that TypeScript types vanish at runtime helps you explain why performance depends on the JavaScript code, not the types.
What if the function used a complex comparison instead of ===? How would that change the time complexity?