AI Hints
Home›TypeScript Tutorial›More About Classes
TypeScript · Lesson 50 of 120

Getters and Setters

Computed properties.

⏱ 2 min read▶ Video at 39:18🎓 Free
Watch this lesson in the TypeScript courseWatch on YouTube ↗Full TypeScript course

A getter looks like a property, but runs code when you read it. A setter runs code when you assign to it. They're handy for computed values, and for checks.

Getters and Setters
From the video: Getters and Setters
  • Looks like a property
  • Runs code
  • Computed and checked

A checked quantity

Total is a getter, computed from price and quantity. The quantity setter refuses negative numbers. Run it. The total updates, and the bad value is rejected.

app.tstypescript
class CartLine {
  private _qty = 1;
  constructor(public price: number) {}

  get total(): number { return this.price * this._qty; }

  get quantity(): number { return this._qty; }
  set quantity(value: number) {
    if (value < 0) throw new Error("Quantity can't be negative");
    this._qty = value;
  }
}

const line = new CartLine(25);
line.quantity = 3;
console.log("Total:", line.total);
try { line.quantity = -2; } catch (e) { console.log((e as Error).message); }
Output
Total: 75
Quantity can't be negative

Summary

Getters compute values on read, and setters check values on write. Next, the classes quiz.

Key takeaways
  • get total()
  • set quantity()
  • Checks
Next up: Classes Quiz — test yourself