0
0
Typescriptprogramming~5 mins

Nested object types in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Nested object types
O(n)
Understanding Time Complexity

When working with nested object types in TypeScript, it's important to understand how accessing or processing these objects affects the time it takes for your program to run.

We want to know how the time needed grows as the nested objects get bigger or deeper.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


interface User {
  id: number;
  profile: {
    name: string;
    address: {
      street: string;
      city: string;
    };
  };
}

function printUserCities(users: User[]) {
  for (const user of users) {
    console.log(user.profile.address.city);
  }
}
    

This code loops through an array of users and prints the city from each user's nested address object.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through the users array once.
  • How many times: Once for each user in the array (n times).
How Execution Grows With Input

As the number of users grows, the time to print all cities grows in a straight line.

Input Size (n)Approx. Operations
1010 city accesses and prints
100100 city accesses and prints
10001000 city accesses and prints

Pattern observation: Doubling the number of users doubles the work done.

Final Time Complexity

Time Complexity: O(n)

This means the time grows directly with the number of users; more users mean more time, but only in a simple, straight line.

Common Mistake

[X] Wrong: "Accessing nested objects makes the time grow much faster, like squared or worse."

[OK] Correct: Accessing nested properties is a fixed number of steps per user, so it does not multiply with input size. The main time cost is still just looping through the users.

Interview Connect

Understanding how nested object access affects time helps you explain your code clearly and shows you can think about efficiency even in simple tasks.

Self-Check

"What if we added a nested loop inside to process each user's friends list? How would the time complexity change?"