How intersection combines types in Typescript - Performance & Efficiency
We want to understand how the time it takes to combine types using intersection grows as the types get bigger.
Specifically, how does the process of merging two types scale when their properties increase?
Analyze the time complexity of the following TypeScript type intersection.
type A = { a: string; b: number; c: boolean };
type B = { b: number; d: string; e: boolean };
type C = A & B;
This code creates a new type C by combining types A and B using intersection.
When combining types, the system checks each property in both types.
- Primary operation: Comparing and merging properties from both types.
- 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 roughly by adding their sizes.
| Input Size (properties per type) | Approx. Operations |
|---|---|
| 10 | About 20 checks (10 + 10) |
| 100 | About 200 checks (100 + 100) |
| 1000 | About 2000 checks (1000 + 1000) |
Pattern observation: The work grows linearly as the total number of properties increases.
Time Complexity: O(n + m)
This means the time to combine two types grows in a straight line with the total number of properties in both types.
[X] Wrong: "Combining two types takes time proportional to the product of their sizes (like n * m)."
[OK] Correct: The process just checks each property once per type, so it adds their sizes instead of multiplying.
Understanding how type operations scale helps you reason about code maintainability and compiler performance, a useful skill in real projects.
"What if we combined three types instead of two? How would the time complexity change?"