TypeScript abstract classes and access modifiers

TypeScript adds access modifiers to classes. A private member is visible only inside the class, a protected member is also visible to subclasses, and public is the default. readonly forbids assignment after construction. These modifiers are checked by the compiler and erased at run time. For hard privacy at run time use JavaScript's #private fields.

TypeScript
interface Describable {
  describe(): string;
}

abstract class Shape implements Describable {
  readonly name: string;
  private static count = 0;

  constructor(name: string) {
    this.name = name;
    Shape.count++;
  }

  abstract area(): number;

  describe(): string {
    return this.name + " with area " + this.area().toFixed(2);
  }

  static total(): number {
    return Shape.count;
  }
}

class Circle extends Shape {
  private radius: number;

  constructor(radius: number) {
    super("circle");
    this.radius = radius;
  }

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

class Rectangle extends Shape {
  private width: number;
  private height: number;

  constructor(width: number, height: number) {
    super("rectangle");
    this.width = width;
    this.height = height;
  }

  area(): number {
    return this.width * this.height;
  }
}

const shapes: Shape[] = [new Circle(1.5), new Rectangle(2, 3.5)];
for (const shape of shapes) {
  console.log(shape.describe());
}
console.log("shapes created: " + Shape.total());
Read the full lesson