typeof type guards in Typescript - Time & Space Complexity
We want to understand how the time it takes to run code with typeof type guards changes as input size grows.
Specifically, how does checking types affect the speed when we handle many values?
Analyze the time complexity of the following code snippet.
function processValues(values: (string | number)[]) {
for (const value of values) {
if (typeof value === 'string') {
console.log(value.toUpperCase());
} else {
console.log(value.toFixed(2));
}
}
}
This code loops through an array and uses typeof to check each item's type before processing.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: A single loop over the array
values. - How many times: Once for each item in the array.
Each item in the array is checked once with typeof and processed accordingly.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 type checks and 10 processing steps |
| 100 | About 100 type checks and 100 processing steps |
| 1000 | About 1000 type checks and 1000 processing steps |
Pattern observation: The work grows directly with the number of items. Double the items, double the work.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of items to check and process.
[X] Wrong: "Using typeof inside a loop makes the code slower in a way that depends on the type of data."
[OK] Correct: The typeof check is very fast and happens once per item, so it does not add extra loops or nested work. The time depends mainly on the number of items, not their types.
Understanding how simple type checks scale helps you explain your code's efficiency clearly and confidently in interviews.
"What if we added a nested loop inside the typeof check for strings? How would the time complexity change?"