Generic constraints with extends in Typescript - Time & Space Complexity
We want to see how the time needed to run code changes when using generic constraints with extends in TypeScript.
Specifically, how does limiting types affect the number of steps the program takes?
Analyze the time complexity of the following code snippet.
function printName<T extends { name: string }>(items: T[]): void {
for (const item of items) {
console.log(item.name);
}
}
const people = [
{ name: 'Alice' },
{ name: 'Bob' },
{ name: 'Charlie' }
];
printName(people);
This function prints the name property of each item in an array, where each item must have a name string.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each item in the array.
- How many times: Once for every element in the input array.
As the number of items grows, the function prints each name one by one.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 print steps |
| 100 | 100 print steps |
| 1000 | 1000 print steps |
Pattern observation: The steps grow directly with the number of items. Double the items, double the steps.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of items in the array.
[X] Wrong: "Using extends makes the function slower because it adds extra checks for types at runtime."
[OK] Correct: The extends constraint only helps TypeScript check types while coding. It does not add any extra steps when the program runs.
Understanding how generic constraints affect code helps you write safe and efficient functions. This skill shows you can think about both correctness and performance.
What if we changed the constraint to T extends { id: number } and printed id instead? How would the time complexity change?