What is getters/setters in TypeScript?
What is getters/setters in TypeScript?
In TypeScript, getters and setters are special methods used to define access to the properties of an object. These methods are also known as accessors and mutators, respectively.
A getter, or accessor, is a method that gets the value of a specific property. It does not take any parameters and returns a value. In TypeScript, you define a getter using the get
keyword followed by a function. The primary purpose of a getter is to return the internal state of an object without the consumer directly accessing the private member variables.
A setter, or mutator, is a method that sets the value of a specific property. It takes one parameter (the new value to set) and does not typically return a value. In TypeScript, you define a setter using the set
keyword followed by a function. Setters allow controlling how important values are updated in an object, which can include validation or even computation before the value is stored.
Here is a simple example of how getters and setters can be implemented in TypeScript:
class Person {
private _name: string;
constructor(name: string) {
this._name = name;
}
get name(): string {
return this._name;
}
set name(value: string) {
if (value.length > 0) {
this._name = value;
} else {
console.error("Invalid name.");
}
}
}
let person = new Person("John");
console.log(person.name); // John
person.name = "Steve"; // sets the name to S...
junior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào