Union vs intersection mental model in Typescript - Performance Comparison
When working with union and intersection types in TypeScript, it's helpful to understand how the operations scale as we combine types.
We want to see how the complexity grows when checking or combining these types.
Analyze the time complexity of the following type checks using union and intersection.
type A = { a: number };
type B = { b: string };
type C = A | B; // union
type D = A & B; // intersection
function checkUnion(x: C) {
if ('a' in x) return x.a;
else return x.b;
}
function checkIntersection(x: D) {
return x.a + x.b.length;
}
This code defines union and intersection types and shows how we access their properties.
Look at how many checks or property accesses happen when using union or intersection types.
- Primary operation: Property existence checks for union, direct property access for intersection.
- How many times: For union, one check per type to decide type; for intersection, all properties accessed directly.
As the number of types combined grows, the checks or accesses increase.
| Input Size (number of types) | Approx. Operations |
|---|---|
| 2 | 2 checks or accesses |
| 5 | 5 checks or accesses |
| 10 | 10 checks or accesses |
Pattern observation: The number of operations grows linearly with the number of types combined.
Time Complexity: O(n)
This means the time to check or access properties grows in direct proportion to the number of types involved.
[X] Wrong: "Union and intersection types have constant time checks regardless of size."
[OK] Correct: Each additional type adds more properties to check or access, so the work grows with the number of types.
Understanding how combining types affects checking helps you reason about code performance and type safety in real projects.
"What if we nested unions inside intersections? How would that affect the time complexity?"