Runtime type checking strategies in Typescript - Time & Space Complexity
When we check types while a program runs, it takes time. We want to know how this time grows as the data gets bigger.
How much longer does type checking take when we have more or bigger inputs?
Analyze the time complexity of the following code snippet.
function isStringArray(arr: unknown[]): boolean {
for (const item of arr) {
if (typeof item !== 'string') {
return false;
}
}
return true;
}
This code checks if every item in an array is a string by looking at each item one by one.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each element in the array.
- How many times: Once for each item until a non-string is found or all items are checked.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Up to 10 checks |
| 100 | Up to 100 checks |
| 1000 | Up to 1000 checks |
Pattern observation: The time grows directly with the number of items because each item is checked once.
Time Complexity: O(n)
This means the time to check types grows in a straight line with the number of items.
[X] Wrong: "Type checking is instant and does not depend on input size."
[OK] Correct: Each item must be checked, so more items mean more work and more time.
Understanding how runtime checks grow with input size helps you explain your code's efficiency clearly and confidently.
"What if we checked nested arrays inside the main array? How would the time complexity change?"