Parameter properties shorthand in Typescript - Time & Space Complexity
Let's see how using parameter properties shorthand affects the time it takes to create objects in TypeScript.
We want to know how the work grows when making many objects this way.
Analyze the time complexity of the following code snippet.
class Person {
constructor(public name: string, public age: number) {}
}
const people: Person[] = [];
for (let i = 0; i < n; i++) {
people.push(new Person(`Name${i}`, i));
}
This code creates n Person objects using parameter properties shorthand inside the constructor.
- Primary operation: Creating a new Person object inside the loop.
- How many times: The loop runs n times, so object creation happens n times.
Each new object takes a small fixed time, and we do this n times.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 object creations |
| 100 | About 100 object creations |
| 1000 | About 1000 object creations |
Pattern observation: The work grows directly with n; doubling n doubles the work.
Time Complexity: O(n)
This means the time to create all objects grows in a straight line as you add more objects.
[X] Wrong: "Using parameter properties shorthand makes object creation faster in a way that changes time complexity."
[OK] Correct: The shorthand just saves typing; the computer still creates each object one by one, so time grows with n.
Understanding how object creation scales helps you explain code efficiency clearly and confidently in interviews.
"What if we added a nested loop inside the constructor that runs m times? How would the time complexity change?"