Type alias for objects in Typescript - Time & Space Complexity
Let's see how the time it takes to run code changes when we use type aliases for objects in TypeScript.
We want to know how the program's work grows as the object size or usage grows.
Analyze the time complexity of the following code snippet.
type User = {
id: number;
name: string;
age: number;
};
function greetUsers(users: User[]) {
users.forEach(user => {
console.log(`Hello, ${user.name}!`);
});
}
This code defines a type alias for a user object and then greets each user in an array.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the array of users with
forEach. - How many times: Once for each user in the array.
As the number of users grows, the number of greetings grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 greetings |
| 100 | 100 greetings |
| 1000 | 1000 greetings |
Pattern observation: The work grows directly with the number of users.
Time Complexity: O(n)
This means the time to greet users grows in a straight line with the number of users.
[X] Wrong: "Using a type alias for objects makes the code run faster or slower."
[OK] Correct: Type aliases only help with code clarity and checking before running. They do not affect how fast the program runs.
Understanding how loops over typed objects behave helps you explain your code clearly and reason about performance in real projects.
What if we changed the array to a nested array of users? How would the time complexity change?