0
0
Typescriptprogramming~5 mins

Combining utility types in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Combining utility types
O(n)
Understanding Time Complexity

When we combine utility types in TypeScript, we want to know how the time to create the new type grows as the input types get bigger.

We ask: How does the work to build the combined type change with input size?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


type Person = { name: string; age: number };
type Contact = { email: string; phone: string };

type PersonContact = Person & Contact;

// PersonContact now has all properties from Person and Contact
    

This code combines two types into one using intersection, merging their properties.

Identify Repeating Operations

Look for how many properties TypeScript processes when combining types.

  • Primary operation: Merging properties from each input type.
  • How many times: Once for each property in both types.
How Execution Grows With Input

As the number of properties in each type grows, the work to combine them grows too.

Input Size (n)Approx. Operations
10About 20 property merges
100About 200 property merges
1000About 2000 property merges

Pattern observation: The work grows roughly by adding the properties from both types, so it grows linearly with the total number of properties.

Final Time Complexity

Time Complexity: O(n)

This means the time to combine types grows in a straight line as the total number of properties increases.

Common Mistake

[X] Wrong: "Combining two types takes constant time no matter their size."

[OK] Correct: Because TypeScript must look at each property to merge them, so more properties mean more work.

Interview Connect

Understanding how utility types combine helps you reason about type operations and their cost, a useful skill when designing complex types in real projects.

Self-Check

"What if we combined three or more types instead of two? How would the time complexity change?"