Skip to the solution
EasyFrontend9 min read

What are access modifiers in TypeScript classes?

190 views

The problem

Question presented to candidate: "What access modifiers does TypeScript give you for class members, what does each one allow, and does private actually keep data private?"

What a strong answer should cover:

  • public (the default), protected (the class and its subclasses) and private (the declaring class only), plus readonly (assign only in the declaration or constructor)
  • Parameter properties: constructor(private readonly id: string) declares and assigns a field in one step
  • These modifiers are compile-time only: they are erased, so private fields show up in JSON.stringify, Object.keys and bracket access, and code that ignores tsc can still change them
  • JavaScript #private fields (supported since TypeScript 3.8) are enforced by the engine at run time; #x in obj is a brand check (TypeScript 4.5)
  • Details interviewers probe: protected access only through an instance of the accessing class (TS2446), private constructors for singletons and factories, and that private members make classes compare nominally

Code / implementation expected: Optional β€” a small class hierarchy showing what each modifier allows and what still happens at run time.

  • access-modifiers

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

9 min read Β· 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

TypeScriptThe four modifiers, and what still runs after tsc rejects it
TypeScriptprivate vs #private, protected access and private constructors

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 13 of 81 in TypeScript

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

How does `using` / `await using` with `Symbol.dispose` work in TypeScript 5.2+?

Continue