TypeScript · Types that pay for themselves

What do public, private, protected and readonly mean?

Easyaccess-modifiersencapsulationclassesUpdated Oct 2026
Quiz this track

Short answer

public, protected and private control compile-time visibility, and readonly prevents reassignment. TypeScript's private is erased at runtime, so it is not a security boundary; hash fields are truly private.

Access modifiers are a compile-time tool for expressing intent. public is the default. protected allows access from subclasses. private restricts access to the declaring class. readonly prevents reassignment after initialization, but it does not make an object deeply immutable.

ts
class Account {
  private balance = 0;
  readonly id: string;

  constructor(id: string) {
    this.id = id;
  }

  deposit(amount: number): void {
    this.balance += amount;
  }

  getBalance(): number {
    return this.balance;
  }
}

Compile-time versus runtime privacy

  • public members are accessible anywhere
  • protected members are accessible in the class and its subclasses
  • private members are accessible only in the declaring class
  • readonly prevents reassignment through the type system
  • Hash-prefixed fields such as #balance are private at runtime

TypeScript's private is erased, so JavaScript code can still reach the property with bracket access. That matters for security-sensitive values and for libraries that receive your objects. Use a hash-prefixed field when runtime privacy is required, and expose behavior through methods rather than mutable state.

readonly is shallow. A readonly array property cannot be reassigned, but its elements can still be mutated unless the element type is also readonly.

Follow-ups you should expect

Interviewers use these to check whether the first answer was understanding or memorisation.

  1. 1Is TypeScript private enforced at runtime?
  2. 2What is the difference between private and #private?
  3. 3Does readonly make an object deeply immutable?
  4. 4When should a member be protected rather than private?

Say it in the interview

public, protected and private control visibility at compile time, and readonly prevents reassignment. TypeScript's private is erased, so JavaScript can still reach the property at runtime; it is not a security boundary. For true runtime privacy I use a hash-prefixed field. I default to the narrowest visibility and expose methods rather than mutable state.

Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.

Related questions

Reading is step one

Now say it out loud.

Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live TypeScript mock interview and get scored feedback on depth, clarity and confidence.