0
0
Typescriptprogramming~5 mins

Generic constraints with extends in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Generic constraints with extends
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

As the number of items grows, the function prints each name one by one.

Input Size (n)Approx. Operations
1010 print steps
100100 print steps
10001000 print steps

Pattern observation: The steps grow directly with the number of items. Double the items, double the steps.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line with the number of items in the array.

Common Mistake

[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.

Interview Connect

Understanding how generic constraints affect code helps you write safe and efficient functions. This skill shows you can think about both correctness and performance.

Self-Check

What if we changed the constraint to T extends { id: number } and printed id instead? How would the time complexity change?