0
0
Typescriptprogramming~5 mins

typeof type guards in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: typeof type guards
O(n)
Understanding Time Complexity

We want to understand how the time it takes to run code with typeof type guards changes as input size grows.

Specifically, how does checking types affect the speed when we handle many values?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


function processValues(values: (string | number)[]) {
  for (const value of values) {
    if (typeof value === 'string') {
      console.log(value.toUpperCase());
    } else {
      console.log(value.toFixed(2));
    }
  }
}
    

This code loops through an array and uses typeof to check each item's type before processing.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: A single loop over the array values.
  • How many times: Once for each item in the array.
How Execution Grows With Input

Each item in the array is checked once with typeof and processed accordingly.

Input Size (n)Approx. Operations
10About 10 type checks and 10 processing steps
100About 100 type checks and 100 processing steps
1000About 1000 type checks and 1000 processing steps

Pattern observation: The work grows directly with the number of items. Double the items, double the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line with the number of items to check and process.

Common Mistake

[X] Wrong: "Using typeof inside a loop makes the code slower in a way that depends on the type of data."

[OK] Correct: The typeof check is very fast and happens once per item, so it does not add extra loops or nested work. The time depends mainly on the number of items, not their types.

Interview Connect

Understanding how simple type checks scale helps you explain your code's efficiency clearly and confidently in interviews.

Self-Check

"What if we added a nested loop inside the typeof check for strings? How would the time complexity change?"