Generic array syntax in Typescript - Time & Space Complexity
We want to understand how the time it takes to work with generic arrays changes as the array grows.
How does the number of steps grow when we use generic arrays in TypeScript?
Analyze the time complexity of the following code snippet.
function printItems<T>(items: T[]): void {
for (const item of items) {
console.log(item);
}
}
const numbers: number[] = [1, 2, 3, 4, 5];
printItems(numbers);
This code prints each item in a generic array, showing how generic array syntax works in TypeScript.
- Primary operation: Looping through each element of the array.
- How many times: Once for each item in the array (n times).
As the array gets bigger, the number of steps grows directly with the number of items.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 steps (print 10 items) |
| 100 | 100 steps (print 100 items) |
| 1000 | 1000 steps (print 1000 items) |
Pattern observation: The steps increase evenly as the array size grows.
Time Complexity: O(n)
This means the time to print items grows in direct proportion to the number of items in the array.
[X] Wrong: "Using generic arrays makes the code slower because of extra type checks at runtime."
[OK] Correct: TypeScript types are erased during compilation, so generics do not add runtime cost or slow down loops.
Understanding how loops over generic arrays behave helps you explain performance clearly and write efficient code in interviews.
"What if we changed the loop to a nested loop over two generic arrays? How would the time complexity change?"