0
0
Typescriptprogramming~5 mins

Default generic types in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Default generic types
O(n)
Understanding Time Complexity

We want to understand how the time it takes to run code with default generic types changes as the input grows.

How does using default types affect the work done when the code runs?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


function wrapInArray<T = number>(item: T): T[] {
  return [item];
}

const result1 = wrapInArray(5);       // Uses default type number
const result2 = wrapInArray('hello'); // Uses string type explicitly

This code defines a function with a default generic type and calls it with different inputs.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Creating a new array with one item.
  • How many times: Once per function call.
How Execution Grows With Input

Each call creates a single array with one element, so the work grows directly with how many times the function is called.

Input Size (n)Approx. Operations
1010 array creations
100100 array creations
10001000 array creations

Pattern observation: The work grows in a straight line with the number of calls.

Final Time Complexity

Time Complexity: O(n)

This means the time grows directly in proportion to how many times the function is called.

Common Mistake

[X] Wrong: "Using default generic types makes the function slower or more complex."

[OK] Correct: The default generic type only sets a type when none is given; it does not add extra work when the function runs.

Interview Connect

Understanding how default generic types affect performance helps you explain your code choices clearly and shows you know how types relate to runtime work.

Self-Check

"What if the function created an array of size n instead of just one item? How would the time complexity change?"