Start Coding

Topics

TypeScript Getters and Setters

Getters and setters are special methods that provide controlled access to object properties in TypeScript. They allow you to define how a property is accessed or modified, enabling better encapsulation and data validation.

Understanding Getters

Getters are methods that retrieve the value of a property. They're defined using the get keyword followed by the property name.


class Circle {
    private _radius: number;

    get radius(): number {
        return this._radius;
    }
}
    

Implementing Setters

Setters are methods that set the value of a property. They're defined using the set keyword followed by the property name.


class Circle {
    private _radius: number;

    set radius(value: number) {
        if (value >= 0) {
            this._radius = value;
        }
    }
}
    

Combining Getters and Setters

Often, getters and setters are used together to provide controlled access to a property:


class Circle {
    private _radius: number;

    get radius(): number {
        return this._radius;
    }

    set radius(value: number) {
        if (value >= 0) {
            this._radius = value;
        } else {
            throw new Error("Radius cannot be negative");
        }
    }
}

const circle = new Circle();
circle.radius = 5; // Sets the radius
console.log(circle.radius); // Gets the radius
    

Benefits of Getters and Setters

  • Encapsulation: Control access to internal properties
  • Validation: Ensure property values meet certain criteria
  • Computed Properties: Calculate values on-the-fly
  • Backward Compatibility: Modify internal implementation without changing public interface

Best Practices

  1. Use getters for read-only properties
  2. Implement validation logic in setters
  3. Keep getter and setter logic simple and focused
  4. Consider using TypeScript's Access Modifiers in conjunction with getters and setters

Related Concepts

To deepen your understanding of TypeScript and object-oriented programming, explore these related topics:

By mastering getters and setters, you'll enhance your ability to create robust and maintainable TypeScript code. These accessor methods are fundamental to implementing encapsulation, a key principle of object-oriented programming.