CodePark/ questions / Classes & enums
START PRACTICINGPRACTICE
Frontend question · TypeScript › Classes & enums

Explain access modifiers and abstract classes in TypeScript. What is the difference between private and #private?

abstract class Shape {
  constructor(protected readonly name: string) {}
  abstract area(): number;
  describe() { return `${this.name}: ${this.area()}`; }
}

class Circle extends Shape {
  #radius: number;
  constructor(radius: number) { super("circle"); this.#radius = radius; }
  area() { return Math.PI * this.#radius ** 2; }
}

Access modifiers control who can use a member. Abstract classes are base classes that cannot be created directly. TypeScript's private is checked only at compile time, while #private is enforced by JavaScript at runtime.

Access modifiers:

  • public is the default. Anyone can use the member.
  • protected members are visible in the class and its subclasses.
  • private members are visible only in the class that declares them.
  • readonly stops reassignment after the constructor runs.

You can write a modifier on a constructor parameter, as in protected readonly name. This declares the property and assigns it in one step. It is called a parameter property.

An abstract class cannot be created with new. It can hold shared code plus abstract members that subclasses must implement.

private vs #private:

  • TypeScript's private is compile-time only. In the output JavaScript, it is a normal property. You can reach it with bracket notation or from plain JavaScript.
  • #radius is a JavaScript private field. The runtime enforces it, so code outside the class truly cannot reach it.
  • public is the default, protected allows subclasses, private allows only the class, and readonly stops reassignment.
  • Parameter properties declare and assign a property in the constructor signature.
  • You cannot create an abstract class with new, and subclasses must implement its abstract members.
  • private is checked only by TypeScript, while #private is enforced at runtime.