0
0
Typescriptprogramming~5 mins

Typeof operator in type context in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: typeof operator in runtime context
O(n)
Understanding Time Complexity

We want to understand how the time needed to check types using the typeof operator grows as the code runs.

Specifically, how does using typeof in a runtime context affect performance when the input size changes?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


const data = [1, 'two', true, 4, 'five'];

function countStrings(arr: unknown[]): number {
  let count = 0;
  for (const item of arr) {
    if (typeof item === 'string') {
      count++;
    }
  }
  return count;
}

countStrings(data);
    

This code counts how many string items are in an array using typeof in a type check.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through each item in the array and checking its type with typeof.
  • How many times: Once for every item in the array (n times, where n is the array length).
How Execution Grows With Input

Each new item adds one more type check, so the work grows steadily as the array grows.

Input Size (n)Approx. Operations
1010 type checks
100100 type checks
10001000 type checks

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

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: "Using typeof in a runtime context is slow and adds extra loops."

[OK] Correct: The typeof check happens inside the existing loop and does not add extra loops or nested checks, so it does not increase the overall time complexity beyond the loop itself.

Interview Connect

Understanding how simple type checks scale with input size helps you reason about performance in real code, showing you can think clearly about how your code behaves as data grows.

Self-Check

"What if we replaced the single loop with nested loops that check types inside each other? How would the time complexity change?"