Nested object types in Typescript - Time & Space 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.
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 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).
As the number of users grows, the time to print all cities grows in a straight line.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 city accesses and prints |
| 100 | 100 city accesses and prints |
| 1000 | 1000 city accesses and prints |
Pattern observation: Doubling the number of users doubles the work done.
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.
[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.
Understanding how nested object access affects time helps you explain your code clearly and shows you can think about efficiency even in simple tasks.
"What if we added a nested loop inside to process each user's friends list? How would the time complexity change?"