Type predicates in practice in Typescript - Time & Space Complexity
We want to see how the time it takes to run code with type predicates changes as input grows.
How does checking types affect the speed when we have many items?
Analyze the time complexity of the following code snippet.
function isString(value: unknown): value is string {
return typeof value === 'string';
}
function filterStrings(items: unknown[]): string[] {
return items.filter(isString);
}
This code filters an array to keep only strings using a type predicate function.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The filter method loops through each item in the array.
- How many times: Once for every item in the input array.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 type checks |
| 100 | About 100 type checks |
| 1000 | About 1000 type checks |
Pattern observation: The number of operations grows directly with the number of items.
Time Complexity: O(n)
This means the time to filter grows in a straight line as the list gets bigger.
[X] Wrong: "Using a type predicate makes the filtering slower than normal because it adds extra checks."
[OK] Correct: The type predicate is just a simple check done once per item, so it does not add extra loops or nested work. The main cost is still just going through the list once.
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 changed the filter to check two different type predicates for each item? How would the time complexity change?"