public / private / protected Access Modifiers & readonly
Last updated: 2026-10-22
public / private / protected Access Modifiers & readonly
Access modifiers control member visibility: public (default, accessible everywhere), private (class-only), protected (class and subclasses). They are compile-time constraints — encapsulation mistakes surface while coding, not after runtime data gets corrupted.
| Group | Functions & Classes |
|---|---|
| Kind | Syntax |
| Strict mode | Not required |
ℹ️ Info The editor transpiles TypeScript to JavaScript and runs it (no type checking); see each example's Output for type-check results.
📝 Syntax
class BankAccount {
public owner: string; // public is the default; written to state intent
private balance: number; // readable/writable only inside the class
constructor(owner: string, initial: number) {
this.owner = owner;
this.balance = initial;
}
deposit(amount: number): void { this.balance += amount; }
getBalance(): number { return this.balance; }
}
⚙️ Parameters
| public | The default modifier: accessible everywhere; writing it out documents intent |
|---|---|
| private | Accessible only inside the class's own methods; external and subclass access are compile errors |
| protected | Available to the class and subclasses, not outside — a controlled extension point for subclasses |
Returns:Modifiers do not change return types; they only constrain who may call or read/write a member.
▶ Example
Edit the code below and click Try it to see the transpiled result:
Output:
Mia: 150
(Runtime output after transpilation; assigning acct.balance from outside is a compile error — only in-class methods may touch it)
💡 Notes
ℹ️ Info private/protected are compile-time only: the field still exists on the object after transpilation (acct.balance works at runtime). For runtime isolation use the JS private field #balance.
ℹ️ Info Instances of the same class may access each other's private members (e.g. reading other.balance inside equals(other: BankAccount)) — that is by design.
⚠️ Note private evaporates after transpilation — never treat it as a security boundary; it guards against accidental misuse, not malicious access.
🏷️ Related Functions & Classes
💡 Related cases
More cases coming soon.
📚 Related tutorials
❓ FAQ
Q private vs the # private field?
A private is a TS compile-time check (bypassable at runtime); #field is language-level privacy (truly inaccessible at runtime). Prefer # in new code; use private when deep TS-type integration matters.
Q When should protected be used?
A For controlled extension points: hook methods in template-method patterns, internal state subclasses need to read. Tighter than public, looser than private.
Q get/set accessors or public fields?
A Use get/set when reads/writes need side effects (validation, caching, derived values); plain storage stays a public field — don't wrap every field in accessors.