Why type narrowing is needed in Typescript - Performance Analysis
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.
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 the loops, recursion, array traversals that repeat.
- Primary operation: The type checks using
typeofhappen once per call. - How many times: Each call does a fixed number of checks (up to 2), no loops or recursion.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Up to 2 type checks |
| 100 | Up to 2 type checks |
| 1000 | Up to 2 type checks |
Pattern observation: The number of operations is constant (up to 2 checks), independent of input size.
Time Complexity: O(1)
This means the time to run stays constant as the input size grows.
[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.
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.
"What if the type checks were inside a loop over an array of values? How would the time complexity change?"