0
0
Typescriptprogramming~5 mins

Type narrowing with typeof in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Type narrowing with typeof
O(n)
Understanding Time Complexity

We want to see how the time it takes to run code changes when we use type checks with typeof.

How does checking a variable's type affect the speed as the input grows?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


function processValue(value: string | number) {
  if (typeof value === 'string') {
    return value.toUpperCase();
  } else {
    return value * 2;
  }
}

const inputs = ["hello", 10, "world", 5];
const results = inputs.map(processValue);
    

This code checks each item's type and processes it differently, then applies this to all items in an array.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The map method loops over each item in the array.
  • How many times: Once for every item in the input array.
How Execution Grows With Input

Each new item adds one more type check and processing step.

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

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

Final Time Complexity

Time Complexity: O(n)

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

Common Mistake

[X] Wrong: "Type checking with typeof makes the code run slower in a way that depends on the type itself."

[OK] Correct: The type check cost is the same for each item and does not depend on the type's content or size, only on how many items we check.

Interview Connect

Understanding how type checks affect performance helps you write clear and efficient code, a skill that shows you think about both correctness and speed.

Self-Check

"What if we replaced map with a nested loop that processes pairs of items? How would the time complexity change?"