← Back to TypeScript Course | Chapter 6: Classes | Lesson 9 of 9

Getters and Setters

Getters and setters provide controlled access to class properties. A getter reads a value like a property, while a setter lets you validate or transform a value before storing it.

Basic Getter

A getter is declared with the get keyword and is accessed like a plain property rather than called like a method, which is useful for exposing a computed or validated value behind ordinary property syntax.

Example: Basic Getter

typescript
class Circle {
  constructor(private radius: number) {}
  get area(): number {
    return 3.14 * this.radius ** 2;
  }
}
const c = new Circle(5);
console.log(c.area); // accessed like a property

Basic Setter

A setter is declared with the set keyword and is invoked using assignment syntax; setters allow a class to intercept every write to a property instead of allowing direct, unchecked field access.

Example: Basic Setter

typescript
class Person {
  private _name: string = "";
  set name(value: string) {
    this._name = value;
  }
  get name(): string {
    return this._name;
  }
}
const p = new Person();
p.name = "Kavya";
console.log(p.name);

Validation with Setters

Setters can validate incoming values before assigning them, throwing or ignoring an invalid update, which helps keep an object's internal state always in a consistent, trustworthy shape.

Example: Validation with Setters

typescript
class Account {
  private _balance: number = 0;
  set balance(value: number) {
    if (value < 0) throw new Error("Balance cannot be negative");
    this._balance = value;
  }
  get balance(): number {
    return this._balance;
  }
}
const acc = new Account();
acc.balance = 100;
console.log(acc.balance);

Computed Getters

A getter can calculate a value from one or more internal properties on the fly, which keeps derived values in sync automatically instead of requiring the class to remember to update a separate cached field.

Example: Computed Getters

typescript
class Rectangle {
  constructor(public width: number, public height: number) {}
  get area(): number {
    return this.width * this.height;
  }
}
console.log(new Rectangle(4, 5).area);

Using Getters and Setters Together

Getters and setters are often paired to provide a property-like interface to callers while keeping the underlying storage private, hiding implementation details behind syntax that still looks like a simple field access.

Example: Using Getters and Setters Together

typescript
class Temperature {
  private _celsius: number = 0;
  get fahrenheit(): number {
    return this._celsius * 9 / 5 + 32;
  }
  set fahrenheit(value: number) {
    this._celsius = (value - 32) * 5 / 9;
  }
}
const t = new Temperature();
t.fahrenheit = 98.6;
console.log(t.fahrenheit);

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.