Generic type variance in Typescript - Time & Space Complexity
When working with generic types in TypeScript, it's helpful to understand how operations scale as input size grows.
We want to see how the use of generic types affects the time it takes for code to run.
Analyze the time complexity of the following code snippet.
function processItems<T>(items: T[]): number {
let count = 0;
for (const item of items) {
if (item) {
count++;
}
}
return count;
}
const numbers = [1, 2, 3, 4, 5];
console.log(processItems(numbers));
This function counts how many items in an array are truthy, using a generic type T.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: A single loop that goes through each item in the array.
- How many times: Once for every item in the input array.
As the number of items grows, the loop runs more times, checking each item once.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks |
| 100 | 100 checks |
| 1000 | 1000 checks |
Pattern observation: The work grows directly with the number of items.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the number of items.
[X] Wrong: "Using generics makes the code slower because it adds extra work."
[OK] Correct: Generics only help with type safety and do not add extra loops or checks at runtime.
Understanding how generic types affect performance helps you write clear and efficient code, a skill valued in many coding challenges and real projects.
"What if we changed the function to process nested arrays of items? How would the time complexity change?"