0
0
Typescriptprogramming~5 mins

Partial type in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Partial type
O(n)
Understanding Time Complexity

Let's explore how the time it takes to create a partial type grows as the size of the original type grows.

We want to know how the work changes when we make some or all properties optional.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


    type User = {
      id: number;
      name: string;
      email: string;
      age: number;
    };

    type PartialUser = Partial;
    

This code creates a new type where all properties of User become optional.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Iterating over each property of the original type.
  • How many times: Once for each property in the type.
How Execution Grows With Input

As the number of properties increases, the work to make them optional grows linearly.

Input Size (number of properties)Approx. Operations
1010 operations
100100 operations
10001000 operations

Pattern observation: The work grows directly with the number of properties.

Final Time Complexity

Time Complexity: O(n)

This means the time to create a partial type grows in a straight line with the number of properties.

Common Mistake

[X] Wrong: "Making a partial type is instant and does not depend on the number of properties."

[OK] Correct: Each property must be processed to become optional, so more properties mean more work.

Interview Connect

Understanding how type transformations scale helps you reason about code maintainability and compiler work behind the scenes.

Self-Check

"What if we used a nested type with properties that are themselves objects? How would the time complexity change?"