xxxxxxxxxx
class Person {
private _name: string = ''; // Private property
// Getter for the name property
get name(): string {
return this._name;
}
// Setter for the name property
set name(newName: string) {
if (newName.length > 0) {
this._name = newName;
} else {
console.error('Name must have at least one character');
}
}
}
// Creating an instance of the Person class
const person = new Person();
// Using the setter to set the name
person.name = 'John';
// Using the getter to get the name
console.log(person.name); // Output: John
// Trying to set an empty name (will trigger the error message)
person.name = ''; // Output: Name must have at least one character
xxxxxxxxxx
// An example of getter and setter
class myClass {
private _x: number;
get x() {
return this._x;
}
// in this example we'll try to set _x to only numbers higher than 0
set x(value) {
if(value <= 0)
throw new Error('Value cannot be less than 0.');
this._x = value;
}
}
let test = new myClass();
test.x = -1; // You'll be getting an error