0
0
Typescriptprogramming~5 mins

Union vs intersection mental model in Typescript - Performance Comparison

Choose your learning style9 modes available
Time Complexity: Union vs intersection mental model
O(n)
Understanding Time Complexity

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.

Scenario Under Consideration

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.

Identify Repeating Operations

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.
How Execution Grows With Input

As the number of types combined grows, the checks or accesses increase.

Input Size (number of types)Approx. Operations
22 checks or accesses
55 checks or accesses
1010 checks or accesses

Pattern observation: The number of operations grows linearly with the number of types combined.

Final Time Complexity

Time Complexity: O(n)

This means the time to check or access properties grows in direct proportion to the number of types involved.

Common Mistake

[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.

Interview Connect

Understanding how combining types affects checking helps you reason about code performance and type safety in real projects.

Self-Check

"What if we nested unions inside intersections? How would that affect the time complexity?"