CodeWithMihir

TypeScript Tutorial

Getters and Setters in TypeScript

Learn how getters and setters work in TypeScript classes, including computed properties, validation, private fields, and practical examples.

Welcome back! I am Mihir, and in this lesson we will learn getters and setters in TypeScript.

Getters and setters let you control how class properties are read and updated.


Basic Getter

class User {
  constructor(public firstName: string, public lastName: string) {}

  get fullName(): string {
    return `${this.firstName} ${this.lastName}`;
  }
}

const user = new User("Mihir", "Soni");
console.log(user.fullName);

Even though fullName is a method internally, you read it like a property.


Basic Setter

class Product {
  private _price: number = 0;

  set price(value: number) {
    if (value < 0) {
      throw new Error("Price cannot be negative");
    }

    this._price = value;
  }

  get price(): number {
    return this._price;
  }
}

Usage:

const product = new Product();
product.price = 500;
console.log(product.price);

Why Use Getters and Setters?

Use them when you want property-like syntax with extra logic.

Good examples:

  • computed values
  • validation
  • formatting
  • hiding internal storage
  • protecting class state

Getter Without Setter

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

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

area can be read, but not assigned.

const circle = new Circle(10);
console.log(circle.area);

Invalid:

circle.area = 100;

Setter Parameter Type

TypeScript checks setter input types.

class Account {
  private _email: string = "";

  set email(value: string) {
    this._email = value.toLowerCase();
  }

  get email(): string {
    return this._email;
  }
}

Invalid:

account.email = 123;

Quick Recap

  • Getters use the get keyword.
  • Setters use the set keyword.
  • Getters are read like properties.
  • Setters are assigned like properties.
  • They are useful for computed values and validation.

Next up, we will learn the Implements Keyword →.