0
0
Typescriptprogramming~5 mins

Why type narrowing is needed in Typescript - Performance Analysis

Choose your learning style9 modes available
Time Complexity: Why type narrowing is needed
O(1)
Understanding Time Complexity

When we write code that checks types, the time it takes depends on how many checks happen.

We want to see how type narrowing affects the number of operations as input grows.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


function process(value: string | number | boolean) {
  if (typeof value === 'string') {
    return value.toUpperCase();
  } else if (typeof value === 'number') {
    return value.toFixed(2);
  } else {
    return value ? 'Yes' : 'No';
  }
}
    

This code checks the type of value and runs different code based on the narrowed type.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The type checks using typeof happen once per call.
  • How many times: Each call does a fixed number of checks (up to 2), no loops or recursion.
How Execution Grows With Input

Explain the growth pattern intuitively.

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

Pattern observation: The number of operations is constant (up to 2 checks), independent of input size.

Final Time Complexity

Time Complexity: O(1)

This means the time to run stays constant as the input size grows.

Common Mistake

[X] Wrong: "Type narrowing adds extra loops or slows down the program a lot."

[OK] Correct: Type narrowing just checks types once per input and helps the program run the right code, so it does not add loops or big delays.

Interview Connect

Understanding how type narrowing affects performance helps you write clear and efficient code, a skill that shows you know how to balance safety and speed.

Self-Check

"What if the type checks were inside a loop over an array of values? How would the time complexity change?"