TL ; DR:
A getter reads a private field. A setter changes it, but only to a value the class allows.
In TypeScript, the keyword get in front of a method makes it the getter. The keyword set in front of a method with the same name makes it the setter. Other code still writes rex.age, as if it were a plain field.
class Dog {
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;
}
}
}
Full lesson:
In the Access Modifiers lesson, getName() let other code read a private field. Often other code must change a field too. A setter allows that, and it checks each new value first.
The getter
Write get age() inside the class. Now reading rex.age runs this method, with no parentheses. It returns the private this._age.
The setter
Write set age(value: number) next to it. Now rex.age = 4 runs that method, with value set to 4.
The private field and the accessors need different names. The underscore in _age is a common way to tell them apart.
The rule
A dog's age can't be negative. So the setter changes this._age only when value is 0 or more. After rex.age = -5, the age stays as it was.
Why not a public field?
With a public age field, any code could set it to -5. Nothing would check it. The accessors keep the rule inside the class. The code that uses rex.age stays the same.
Your task
The Dog class keeps its age in the private _age. Add a getter age that returns it. Add a setter age that ignores negative values.
The code below the class creates rex, then reads and sets rex.age.
Expected output:
Rex is 3
Rex is still 3
Rex is 4Free plan: 30 tutor messages. Premium is unlimited.
