0
0
Typescriptprogramming~5 mins

Type erasure and its consequences in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Type erasure and its consequences
O(n)
Understanding Time 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.

Scenario Under Consideration

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.

Identify Repeating Operations

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.
How Execution Grows With Input

As the array gets bigger, the function checks more items.

Input Size (n)Approx. Operations
10Up to 10 checks
100Up to 100 checks
1000Up to 1000 checks

Pattern observation: The number of checks grows directly with the size of the array.

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows in a straight line as the input gets bigger.

Common Mistake

[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.

Interview Connect

Understanding that TypeScript types vanish at runtime helps you explain why performance depends on the JavaScript code, not the types.

Self-Check

What if the function used a complex comparison instead of ===? How would that change the time complexity?