Typeof operator in type context in Typescript - Time & Space Complexity
We want to understand how the time needed to check types using the typeof operator grows as the code runs.
Specifically, how does using typeof in a runtime context affect performance when the input size changes?
Analyze the time complexity of the following code snippet.
const data = [1, 'two', true, 4, 'five'];
function countStrings(arr: unknown[]): number {
let count = 0;
for (const item of arr) {
if (typeof item === 'string') {
count++;
}
}
return count;
}
countStrings(data);
This code counts how many string items are in an array using typeof in a type check.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each item in the array and checking its type with
typeof. - How many times: Once for every item in the array (n times, where n is the array length).
Each new item adds one more type check, so the work grows steadily as the array grows.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 type checks |
| 100 | 100 type checks |
| 1000 | 1000 type checks |
Pattern observation: The number of operations grows directly in step with the input size.
Time Complexity: O(n)
This means the time to finish grows in a straight line as the input gets bigger.
[X] Wrong: "Using typeof in a runtime context is slow and adds extra loops."
[OK] Correct: The typeof check happens inside the existing loop and does not add extra loops or nested checks, so it does not increase the overall time complexity beyond the loop itself.
Understanding how simple type checks scale with input size helps you reason about performance in real code, showing you can think clearly about how your code behaves as data grows.
"What if we replaced the single loop with nested loops that check types inside each other? How would the time complexity change?"