Consider this TypeScript class with typed getter and setter. What will be printed when the code runs?
class Person { private _age: number = 0; get age(): number { return this._age; } set age(value: number) { if (value < 0) { this._age = 0; } else { this._age = value; } } } const p = new Person(); p.age = -5; console.log(p.age);
Look at how the setter handles negative values.
The setter checks if the value is less than 0. If yes, it sets _age to 0. So, setting p.age = -5 results in _age being 0. The getter returns this value.
Look at this TypeScript class with only a getter. What happens when we try to assign a value to the property?
class Circle { private _radius: number = 5; get radius(): number { return this._radius; } } const c = new Circle(); c.radius = 10; console.log(c.radius);
Think about whether you can assign to a getter-only property in TypeScript.
In TypeScript, a property with only a getter is read-only. Trying to assign to it causes a compilation error.
Examine this TypeScript class. Why does setting value cause a stack overflow?
class Counter { private _count = 0; get count(): number { return this._count; } set count(value: number) { this.count = value; // Problem here } } const counter = new Counter(); counter.count = 5;
Look at what happens inside the setter when assigning this.count = value.
The setter calls this.count = value, which calls the setter again, causing infinite recursion and stack overflow.
Choose the option that correctly defines a getter and setter for a name property of type string.
Check the types of getter return and setter parameter, and the setter body.
Option D correctly types the getter return as string and setter parameter as string. Setter assigns value to private field without returning anything.
Given this TypeScript class with a getter that filters items, how many items does filteredItems contain?
class Store { private items: number[] = [1, 2, 3, 4, 5, 6]; get filteredItems(): number[] { return this.items.filter(x => x % 2 === 0); } } const store = new Store(); const filtered = store.filteredItems;
Count how many even numbers are in the original array.
The original array has 6 numbers: 1,2,3,4,5,6. Even numbers are 2,4,6, so 3 items.