0
0
Typescriptprogramming~5 mins

Migrating JavaScript to TypeScript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Migrating JavaScript to TypeScript
O(n)
Understanding Time Complexity

When moving code from JavaScript to TypeScript, it's important to understand how the added type checks affect the program's speed.

We want to see how the program's running time changes as the input grows after migration.

Scenario Under Consideration

Analyze the time complexity of this TypeScript function that processes an array of numbers.


function sumPositiveNumbers(nums: number[]): number {
  let sum = 0;
  for (const num of nums) {
    if (num > 0) {
      sum += num;
    }
  }
  return sum;
}
    

This function adds up all positive numbers in the input array.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: A single loop that goes through each number in the array once.
  • How many times: Exactly once for each element in the input array.
How Execution Grows With Input

As the input array gets bigger, the function checks each number once, so the work grows steadily.

Input Size (n)Approx. Operations
10About 10 checks and additions
100About 100 checks and additions
1000About 1000 checks and additions

Pattern observation: The number of operations grows directly with the input size.

Final Time Complexity

Time Complexity: O(n)

This means the time it takes grows in a straight line with the number of items.

Common Mistake

[X] Wrong: "Adding TypeScript types makes the code run slower because of extra checks at runtime."

[OK] Correct: TypeScript checks happen only during development and do not add runtime overhead, so the running time depends on the code logic, not the types.

Interview Connect

Understanding how adding types affects your code helps you write clear, maintainable programs without worrying about slowing them down.

Self-Check

"What if we changed the function to check pairs of numbers instead of single numbers? How would the time complexity change?"