Getter and setter with types in Typescript - Time & Space Complexity
Let's see how the time it takes to run code with getters and setters changes as we use more data.
We want to know how the number of operations grows when we access or change values using getters and setters.
Analyze the time complexity of the following code snippet.
class Person {
private _age: number;
constructor(age: number) {
this._age = age;
}
get age(): number {
return this._age;
}
set age(value: number) {
if (value >= 0) {
this._age = value;
}
}
}
const people: Person[] = [];
for (let i = 0; i < 1000; i++) {
people.push(new Person(i));
}
for (const person of people) {
console.log(person.age);
person.age = person.age + 1;
}
This code creates many Person objects, then reads and updates their age using getters and setters.
- Primary operation: Looping through the array of Person objects to get and set age.
- How many times: Once for each person in the array (1000 times in this example).
Each person's age is accessed and updated once, so the total work grows directly with the number of people.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 20 (10 gets + 10 sets) |
| 100 | About 200 (100 gets + 100 sets) |
| 1000 | About 2000 (1000 gets + 1000 sets) |
Pattern observation: The number of operations grows in a straight line as the input size increases.
Time Complexity: O(n)
This means the time to get and set ages grows directly with how many Person objects there are.
[X] Wrong: "Getters and setters add hidden loops making the code slower than a simple property."
[OK] Correct: Getters and setters run just like normal property access, so they don't add extra loops or slow down the code beyond the main loop.
Understanding how getters and setters affect performance helps you explain your code clearly and shows you know how data access scales in real projects.
"What if the setter included a loop inside it? How would the time complexity change when updating ages?"
Practice
What is the main purpose of using getter and setter in TypeScript classes?
Solution
Step 1: Understand getter and setter roles
Getters and setters allow controlled access to class properties, letting you add logic when reading or writing values.Step 2: Recognize type safety benefit
Using types with getters and setters ensures only valid data is assigned or returned, keeping data safe.Final Answer:
To control how properties are accessed and modified with type safety -> Option CQuick Check:
Getter and setter purpose = control access + type safety [OK]
- Thinking getters/setters create new classes
- Believing they improve function speed
- Confusing them with variable declarations
Which of the following is the correct syntax to define a typed getter for a property name of type string in a TypeScript class?
class Person {
private _name: string;
constructor(name: string) {
this._name = name;
}
// What is the correct getter syntax here?
}Solution
Step 1: Recall getter syntax in TypeScript
The getter uses the keywordget, followed by the property name, parentheses, and a return type.Step 2: Check return type matches property type
The getter must return astringsince_nameis a string.Final Answer:
get name(): string { return this._name; } -> Option AQuick Check:
Getter syntax = get + name() + return type [OK]
- Omitting parentheses after getter name
- Using wrong keyword like 'getter'
- Setting return type to void instead of string
What will be the output of the following TypeScript code?
class Counter {
private _count: number = 0;
get count(): number {
return this._count;
}
set count(value: number) {
if (value >= 0) {
this._count = value;
}
}
}
const c = new Counter();
c.count = 5;
c.count = -3;
console.log(c.count);Solution
Step 1: Analyze setter behavior
The setter only updates_countif the new value is >= 0. Setting to 5 updates it, setting to -3 is ignored.Step 2: Check final value returned by getter
The getter returns the current_count, which remains 5 after the invalid -3 assignment.Final Answer:
5 -> Option BQuick Check:
Setter blocks negative, final count = 5 [OK]
- Assuming setter accepts negative values
- Expecting count to be -3 after invalid set
- Confusing initial value with final output
Identify the error in this TypeScript class using getter and setter:
class User {
private _age: number;
get age(): number {
return this._age;
}
set age(value: string) {
this._age = Number(value);
}
}Solution
Step 1: Compare getter and setter types
The getter returns a number, so the setter should accept a number to keep types consistent.Step 2: Identify mismatch in setter parameter
The setter takes a string but assigns to a number property, causing a type mismatch.Final Answer:
Setter parameter type should be number, not string -> Option AQuick Check:
Setter param type must match property type [OK]
- Allowing setter param type different from property
- Thinking getter return type should change
- Believing setter can't convert types
Given this TypeScript class, what will console.log(user.fullName); output?
class User {
private _firstName: string;
private _lastName: string;
constructor(firstName: string, lastName: string) {
this._firstName = firstName;
this._lastName = lastName;
}
get fullName(): string {
return `${this._firstName} ${this._lastName}`;
}
set fullName(name: string) {
const parts = name.split(' ');
if (parts.length === 2) {
[this._firstName, this._lastName] = parts;
}
}
}
const user = new User('Jane', 'Doe');
user.fullName = 'John Smith';
console.log(user.fullName);Solution
Step 1: Understand setter logic
The setter splits the input string by space and updates_firstNameand_lastNameonly if there are exactly two parts.Step 2: Apply setter and check getter output
SettingfullNameto 'John Smith' updates the names. The getter then returns 'John Smith'.Final Answer:
John Smith -> Option DQuick Check:
Setter splits and updates names, getter returns combined string [OK]
- Assuming original names stay after setter call
- Expecting only first or last name to change
- Ignoring setter condition on split length
Ready to prove it?
Pass the test and this pattern moves unknown
