#typescript #oop #classes

Day 11: Static Members and Getters/Setters

Static vs Instance

Welcome to Day 11! Today we look at how to store data on the class itself, rather than the object.

Static Members

A static property or method belongs to the Class, not the Object.

class Grid {
  static origin = { x: 0, y: 0 };

  calculateDistanceFromOrigin(point: { x: number; y: number }) {
    let xDist = (point.x - Grid.origin.x);
    let yDist = (point.y - Grid.origin.y);
    return Math.sqrt(xDist * xDist + yDist * yDist) / this.scale;
  }
  constructor (public scale: number) { }
}

Grid.origin = { x: 10, y: 10 }; // accessing static member

Common use cases: Helper functions, Constants, Configuration.

Getters and Setters

TypeScript supports get and set accessors. They allow you to add logic when reading or writing a property.

class Employee {
  private _fullName: string = "";

  get fullName(): string {
    return this._fullName;
  }

  set fullName(newName: string) {
    if (newName && newName.length > 50) {
      throw new Error("Name is too long.");
    }
    this._fullName = newName;
  }
}

let emp = new Employee();
emp.fullName = "Bob Smith"; // Calls setter
if (emp.fullName) {         // Calls getter
  console.log(emp.fullName);
}

Note: To use accessors, you might need to target ES5 or higher in your tsconfig.json.

Challenge for Today

  1. Create a class Counter.
  2. Add a static property count initialized to 0.
  3. Every time the constructor is called (new Counter()), increment Counter.count.
  4. Verify that creating 5 instances results in Counter.count being 5.
  5. Add a getter currentCount to read the value safely.

See you on Day 12 where we merge worlds: Implementing Interfaces in Classes!