Type narrowing with typeof in Typescript - Time & Space 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?
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 the loops, recursion, array traversals that repeat.
- Primary operation: The
mapmethod loops over each item in the array. - How many times: Once for every item in the input array.
Each new item adds one more type check and processing step.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 type checks and processings |
| 100 | About 100 type checks and processings |
| 1000 | About 1000 type checks and processings |
Pattern observation: The work grows directly with the number of items.
Time Complexity: O(n)
This means the time to finish grows in a straight line as the input list gets bigger.
[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.
Understanding how type checks affect performance helps you write clear and efficient code, a skill that shows you think about both correctness and speed.
"What if we replaced map with a nested loop that processes pairs of items? How would the time complexity change?"