Combining utility types in Typescript - Time & Space 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?
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.
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.
As the number of properties in each type grows, the work to combine them grows too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 20 property merges |
| 100 | About 200 property merges |
| 1000 | About 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.
Time Complexity: O(n)
This means the time to combine types grows in a straight line as the total number of properties increases.
[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.
Understanding how utility types combine helps you reason about type operations and their cost, a useful skill when designing complex types in real projects.
"What if we combined three or more types instead of two? How would the time complexity change?"