Getters and setters let you intercept property reads and writes on an object. The caller uses normal dot notation, but under the hood you control what happens.
Creating a Getter in TypeScript
Use the get keyword before a method name:
class MyClass {
private _myProperty: string = 'default value';
get myProperty(): string {
return this._myProperty;
}
}
const myObject = new MyClass();
console.log(myObject.myProperty); // Output: 'default value'Creating a Setter in TypeScript
Add a setter with the set keyword to handle writes:
class MyClass {
private _myProperty: string = 'default value';
get myProperty(): string {
return this._myProperty;
}
set myProperty(value: string) {
this._myProperty = value;
}
}
const myObject = new MyClass();
myObject.myProperty = 'new value';
console.log(myObject.myProperty); // Output: 'new value'Common use cases for Getters and Setters
A setter can validate or clamp a value before storing it:
class MyClass {
private _myProperty: number = 0;
get myProperty(): number {
return this._myProperty;
}
set myProperty(value: number) {
if (value < 0) {
this._myProperty = 0;
} else if (value > 100) {
this._myProperty = 100;
} else {
this._myProperty = value;
}
}
}
const myObject = new MyClass();
myObject.myProperty = -10;
console.log(myObject.myProperty); // Output: 0
myObject.myProperty = 200;
console.log(myObject.myProperty); // Output: 100
myObject.myProperty = 50;
console.log(myObject.myProperty); // Output: 50Getters also work well for derived values:
class MyClass {
private _myArray: number[] = [];
get myArrayLength(): number {
return this._myArray.length;
}
addValueToMyArray(value: number) {
this._myArray.push(value);
}
}
const myObject = new MyClass();
myObject.addValueToMyArray(1);
myObject.addValueToMyArray(2);
myObject.addValueToMyArray(3);
console.log(myObject.myArrayLength); // Output: 3Conclusion
Getters and setters are most valuable when the implementation needs to change without breaking the public API — validation, computed properties, and lazy initialization all fit naturally here.