Typescript Foundations / Class & Object Oriented Typescript

Getters and Setters

🔒 Getters and Setters

Getters and Setters let you control how a class property is read and updated.

  • Getter (get) → Used to read a property's value.

  • Setter (set) → Used to update a property's value. You can also validate or modify the value before storing it.

Note: They are written like methods but used like normal properties (without ()).


✅ Basic Example

🔍 Explanation

  • _age is a private variable, so it cannot be accessed directly.

  • get age() returns the value of _age.

  • set age() updates _age only if the value is valid.

  • If a negative age is given, it throws an error.


🤔 Why Use Getters and Setters?

Benefit

Explanation

✅ Encapsulation

Keeps data private and controlled.

✅ Validation

Checks values before storing them.

✅ Better Control

You can format or modify data while getting or setting it.


✨ Getter Only (Read-Only Property)

Sometimes a value should only be read, not changed.

class Circle {
  constructor(private radius: number) {}

  get area(): number {
    return Math.PI * this.radius ** 2;
  }
}

const c = new Circle(10);

console.log(c.area);

// c.area = 100;   // Error

🔍 Explanation

  • area is calculated using the radius.

  • Since there is only a getter, area is read-only.

  • You can access it but cannot assign a new value.


🧠 Another Example

class Config {
  private _env: string = "dev";

  get env() {
    return this._env.toUpperCase();
  }

  set env(value: string) {
    this._env = value.toLowerCase();
  }
}

const config = new Config();

config.env = "PROD";

console.log(config.env); // PROD

🔍 Explanation

  • The setter stores the value as lowercase ("prod").

  • The getter returns it in uppercase ("PROD").

  • This lets you control how data is stored and displayed.


📝 Best Practices

  • ✅ Use get to return or calculate a value.

  • ✅ Use set to validate or modify input.

  • ✅ Use a private variable (like _age) to store the actual value.


📌 Summary

Concept

Syntax

Getter

get propertyName() {}

Setter

set propertyName(value) {}

Access

object.property

Update

object.property = value

Easy Trick:
Getter = Get (Read) 📖
Setter = Set (Write/Update) ✏️

Remember: You use getters and setters like normal properties, not like methods.

person.age;      // ✅ Correct
person.age = 30; // ✅ Correct

person.age();    // ❌ Wrong