Intersection type syntax in Typescript - Time & Space Complexity
Let's see how the time cost grows when using intersection types in TypeScript.
We want to know how combining types affects the work the program does.
Analyze the time complexity of the following code snippet.
type A = { name: string };
type B = { age: number };
function combine(objA: A, objB: B): A & B {
return { ...objA, ...objB };
}
const person = combine({ name: 'Alice' }, { age: 30 });
This code merges two objects into one using an intersection type.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Copying properties from both objects using spread syntax.
- How many times: Once per property in each object.
As the number of properties in the objects grows, the copying work grows too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 20 property copies (10 from each object) |
| 100 | About 200 property copies |
| 1000 | About 2000 property copies |
Pattern observation: The work grows roughly in direct proportion to the total number of properties combined.
Time Complexity: O(n)
This means the time to combine objects grows linearly with the total number of properties.
[X] Wrong: "Intersection types make the program run slower exponentially because they combine types."
[OK] Correct: Intersection types only combine properties, so the work grows linearly with property count, not exponentially.
Understanding how combining types affects performance helps you write clear and efficient code, a skill valued in real projects.
"What if we combined three or more objects instead of two? How would the time complexity change?"