Generic conditional constraints in Typescript - Time & Space Complexity
We want to understand how the time needed to run code with generic conditional constraints changes as input grows.
How does the program's work increase when using these constraints with different input sizes?
Analyze the time complexity of the following code snippet.
function processItems<T extends { length: number }>(items: T): number {
let total = 0;
for (let i = 0; i < items.length; i++) {
total += i;
}
return total;
}
const result = processItems('hello');
This function uses a generic type with a condition that the input has a length property, then loops over that length.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: A for-loop running from 0 up to the length of the input.
- How many times: Exactly as many times as the input's length.
As the input length grows, the loop runs more times, increasing work linearly.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 |
| 100 | 100 |
| 1000 | 1000 |
Pattern observation: The work grows directly in proportion to 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: "Because of the generic constraint, the loop runs a fixed number of times regardless of input size."
[OK] Correct: The loop depends on the actual length property of the input, which changes with input size, so the work grows with input length.
Understanding how generic constraints affect loops helps you explain how your code scales, a key skill in real projects and interviews.
"What if the generic constraint required the input to have two nested arrays each with their own length? How would the time complexity change?"