Constructor parameter types in Typescript - Time & Space Complexity
Let's see how the time it takes to run code changes when we use constructor parameters in TypeScript classes.
We want to know how the number of operations grows as we create more objects with parameters.
Analyze the time complexity of the following code snippet.
class Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
}
const people: Person[] = [];
for (let i = 0; i < n; i++) {
people.push(new Person(`Name${i}`, i));
}
This code creates a list of Person objects, each with a name and age passed to the constructor.
- Primary operation: Creating a new Person object inside a loop.
- How many times: The loop runs n times, so the constructor runs n times.
Each time we add one more person, we do one more constructor call and one more push to the array.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 constructor calls and 10 pushes |
| 100 | About 100 constructor calls and 100 pushes |
| 1000 | About 1000 constructor calls and 1000 pushes |
Pattern observation: The number of operations grows directly with n, so doubling n doubles the work.
Time Complexity: O(n)
This means the time to create all objects grows in a straight line as we add more items.
[X] Wrong: "The constructor runs only once, so the time is constant regardless of n."
[OK] Correct: The constructor runs every time we create a new object, so it runs n times when we create n objects.
Understanding how constructors affect performance helps you explain object creation costs clearly and confidently in real projects.
"What if the constructor did some extra work inside a loop for each object? How would the time complexity change?"
Practice
Solution
Step 1: Understand constructor parameter types
Constructor parameter types define what type of values the constructor expects to receive when creating an instance of the class.Step 2: Identify the purpose of parameter types
They help TypeScript check for errors before running the code by ensuring the right types are passed.Final Answer:
It tells what kind of values the constructor expects when creating an object. -> Option DQuick Check:
Constructor parameter types = Define expected input types [OK]
- Thinking parameter types speed up runtime
- Confusing parameter types with method creation
- Believing parameter types rename classes
Solution
Step 1: Review TypeScript constructor syntax
In TypeScript, parameter types are declared after the parameter name with a colon, likename: string.Step 2: Check each option
constructor(name: string, age: number) {} uses correct syntax with colons and types. Options A, C, and D use invalid syntax.Final Answer:
constructor(name: string, age: number) {} -> Option AQuick Check:
Parameter types use colon syntax [OK]
- Omitting colons between name and type
- Using commas or arrows instead of colons
- Placing types after parentheses
class Person {
constructor(public name: string, private age: number) {}
getAge() { return this.age; }
}
const p = new Person('Alice', 30);
console.log(p.name);
console.log(p.getAge());Solution
Step 1: Understand public and private in constructor
Thepublic namecreates a public property accessible outside. Theprivate agecreates a private property accessible only inside the class.Step 2: Check console.log outputs
p.nameprints 'Alice' because it's public.p.getAge()returns 30 because the method accesses privateageinternally.Final Answer:
Alice 30 -> Option BQuick Check:
Public accessible, private via method [OK]
- Expecting private properties accessible outside
- Confusing undefined with private access
- Thinking private causes runtime error
class Car {
constructor(make: string, year: number) {
this.make = make;
this.year = year;
}
}Solution
Step 1: Check class properties and constructor assignments
Step 2: Check class properties
The class does not declare properties 'make' and 'year' before assigning them in the constructor, which causes an error: Property 'make' does not exist on type 'Car'.Final Answer:
Class properties 'make' and 'year' are missing -> Option CQuick Check:
Declare class properties before use [OK]
- Ignoring missing property declarations
- Thinking constructor parameters auto-create properties
- Expecting return type in constructor
Book that takes a title (string), pages (number), and an optional author (string). Which constructor declaration correctly types these parameters and allows creating a Book by omitting the author argument (leaving author as undefined)?Solution
Step 1: Understand optional parameters in TypeScript
Optional parameters are marked with a question mark?after the parameter name, allowing them to be omitted when calling the constructor, leaving the parameterundefined.Step 2: Evaluate each option
constructor(title: string, pages: number, author?: string = '') {}:author?: string = ''-- omitting sets to'', notundefined. constructor(title: string, pages: number, author: string = '') {}:author: string = ''-- omitting sets to''. constructor(title: string, pages: number, author: string) {} requiresauthor. constructor(title: string, pages: number, author?: string) {}:author?: string-- omitting leavesundefined.Final Answer:
constructor(title: string, pages: number, author?: string) {} -> Option AQuick Check:
Optional params use ? after name [OK]
- Using default value without ? for optional
- Forgetting to mark optional parameters
- Mixing optional and default syntax incorrectly
Ready to prove it?
Pass the test and this pattern moves unknown
