Partial type in Typescript - Time & Space 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.
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 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.
As the number of properties increases, the work to make them optional grows linearly.
| Input Size (number of properties) | Approx. Operations |
|---|---|
| 10 | 10 operations |
| 100 | 100 operations |
| 1000 | 1000 operations |
Pattern observation: The work grows directly with the number of properties.
Time Complexity: O(n)
This means the time to create a partial type grows in a straight line with the number of properties.
[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.
Understanding how type transformations scale helps you reason about code maintainability and compiler work behind the scenes.
"What if we used a nested type with properties that are themselves objects? How would the time complexity change?"