Custom type guard functions in Typescript - Time & Space Complexity
We want to understand how the time it takes to check types grows as we use custom type guard functions.
How does the number of checks change when the input size changes?
Analyze the time complexity of the following code snippet.
function isStringArray(value: unknown): value is string[] {
return Array.isArray(value) && value.every(item => typeof item === 'string');
}
const data = ['apple', 'banana', 'cherry'];
const result = isStringArray(data);
This code checks if a value is an array of strings by testing each item.
- Primary operation: The
everymethod loops through each item in the array. - How many times: It runs once for each element in the input array.
As the array gets bigger, the number of checks grows in a straight line.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 type checks |
| 100 | 100 type checks |
| 1000 | 1000 type checks |
Pattern observation: The time grows directly with the number of items.
Time Complexity: O(n)
This means the time to check grows in direct proportion to the number of items in the array.
[X] Wrong: "The type guard runs in constant time no matter the array size."
[OK] Correct: Because it checks each item one by one, the time grows as the array grows.
Understanding how type guards scale helps you write efficient checks and shows you think about performance in real code.
What if the type guard also checked nested arrays inside the main array? How would the time complexity change?