Classes & Access Modifiers
Mark class properties and methods `public`, `private` or `protected` to control what outside code can touch.
What is it?
In a plain JavaScript class, every property and method is reachable from outside. Nothing stops other code reading or overwriting an internal detail, like a bank account's raw balance.
TypeScript adds three access modifiers for class members:
public(the default): reachable from anywhere, like plain JavaScript.private: reachable only from inside the class.protected: reachable from the class and any class that extends it, but not from outside.
The compiler enforces these. Accessing a private member from outside the class is an error before the code runs.
Explain like I'm 10
Think of a class as a house. public is the front porch: anyone can walk up. private is a locked room only the owner can open. protected is the family room: the owner's kids (subclasses) can use it, but a stranger off the street can't.
Examples
public, private, and enforcement
class BankAccount {
public accountHolder: string;
private balance: number;
constructor(accountHolder: string, startingBalance: number) {
this.accountHolder = accountHolder;
this.balance = startingBalance;
}
public deposit(amount: number): void {
this.balance += amount; // fine — inside the class
}
public getBalance(): number {
return this.balance;
}
}
const account = new BankAccount("Lena", 100);
account.deposit(50);
console.log(account.balance);
// Error: Property 'balance' is private and only accessible within class 'BankAccount'.balance can only be read or changed by methods inside BankAccount. Outside code must use deposit and getBalance.
protected and inheritance
class Animal {
protected name: string;
constructor(name: string) {
this.name = name;
}
}
class Dog extends Animal {
bark(): string {
return `${this.name} says woof!`; // OK — protected is visible in subclasses
}
}
const dog = new Dog("Rex");
console.log(dog.name);
// Error: Property 'name' is protected and only accessible
// within class 'Animal' and its subclasses.
// A shorthand: declaring and assigning a parameter in one step
class Cat {
constructor(private lives: number = 9) {}
loseLife(): number {
return --this.lives;
}
}Dog can use this.name because protected includes subclasses, but code outside the class hierarchy still can't. The Cat example shows a shorthand: a modifier on a constructor parameter both declares and assigns the property.
How it works
Access modifiers are checked only at compile time. For each member, the compiler knows its modifier and where the accessing code is (same class, subclass or outside), and reports any access the rule doesn't allow.
After compiling, the checks are gone. JavaScript has no concept of this "private" (its newer #private field syntax is a separate feature), so at runtime the property is still reachable by code that bypasses the type checker, such as plain untyped JavaScript calling the compiled code.
Why does it exist?
Classes often hold internal state: a cache, a counter, a raw value that should only change through a method that keeps it valid. Access modifiers enforce that boundary, steering other code to the public methods instead of changing internal state directly, so the class's guarantees hold.
When to use it
Make a member private when outside code has no good reason to touch it: raw internal state, or helper methods that are just steps of a larger public method. Use protected when subclasses need access but outside code shouldn't have it.
When not to use it
Don't make things private out of habit. If a property is meant to be read or set freely (like a simple data holder with no rules to protect), public (the default) is simpler. Over-restricting forces callers into awkward workarounds.
Common mistakes
Assuming
privateblocks access at runtime. It's compile-time only, unless you use JavaScript's own#fieldprivate syntax.Making every property
privateby reflex, even ones meant to be read from outside, which forces pointless getter methods.Using
protectedwhen you meantprivate, letting subclasses depend on internal details that were never part of the contract.
Practice exercises
- Easy:
Write a class
Counterwith aprivate count: numberfield and publicincrement()andgetCount()methods. Try accessingcountfrom outside to see the error. - Medium:
Write a base class
Vehiclewithprotected speed: numberand a subclassCarwith a method that usesthis.speed. Then accessspeedfrom outside both classes to confirm it's blocked. - Hard:
Rewrite
Counterusing constructor-parameter shorthand (constructor(private count: number = 0) {}). In a comment, explain what changed compared to declaring the field separately.
Interview questions
What do `public`, `private`, and `protected` each allow, in terms of what code can access the member?
public (the default): anywhere. private: only inside the declaring class. protected: the declaring class and any class that extends it, but not outside code.
What access modifier does a class member get if you don't write one explicitly?
public. It's the default and behaves like a plain JavaScript class member, with no restriction.
How does the compiler decide whether a given piece of code is allowed to access a class member?
It checks the member's modifier against where the accessing code is (the declaring class, a subclass, or outside) and flags any access the modifier doesn't allow from there.
Do access modifiers like `private` and `protected` exist as a runtime concept in the compiled JavaScript?
No, the check is compile-time only. After compiling, it's an ordinary property with no restriction, unless you use JavaScript's native #field syntax.
Given `class BankAccount { private balance: number; ... }` and `const account = new BankAccount(...); console.log(account.balance);`, why does this fail to compile?
balance is private, so only methods inside BankAccount can access it. The console.log is outside the class.
Why does `BankAccount` expose `deposit()` and `getBalance()` as public methods instead of just making `balance` public directly?
Keeping balance private forces changes through deposit, which can enforce rules (like never going negative). Outside code can't overwrite the raw value and leave it invalid.
What problem do access modifiers solve that a plain JavaScript class doesn't address on its own?
In plain JavaScript every member is reachable from outside, so other code can read or overwrite internal details. Access modifiers make TypeScript flag that as a compile-time error.
What's the difference between `private` and `protected`?
private members are reachable only inside the declaring class. protected members are also reachable from subclasses. Both block unrelated outside code.
Given `class Animal { protected name: string; ... }` and `class Dog extends Animal { bark() { return this.name; } }`, why does `this.name` compile fine inside `bark()`?
protected includes subclasses, and Dog extends Animal, so Dog's methods can read this.name.
Using the same `Animal`/`Dog` classes, why does `dog.name` fail when accessed from completely outside both classes?
protected only allows the declaring class and its subclasses' own code. A plain dog.name outside that hierarchy is rejected, just as private would reject it.
The topic's analogy describes `protected` as being open to "the family" but not "a visitor off the street" — concretely, whose code counts as family here?
Code inside the declaring class, and code inside any class that extends it, however many levels deep. Everything else is an outside visitor.
You have a `Vehicle` base class with an internal `speed` field that only `Vehicle` and its subclasses should touch. Which modifier fits, and why not the other two?
protected. private would block subclasses from using speed, and public would let any outside code touch it. Only protected means "the class and its subclasses, nothing else."
What is constructor-parameter shorthand, and what two things does writing `constructor(private lives: number = 9) {}` do at once?
A modifier on a constructor parameter both declares lives as a class property and assigns it from the argument. One line replaces a field declaration plus this.lives = lives; in the constructor.
Compare `constructor(private lives: number = 9) {}` to declaring `private lives: number;` as a field and assigning it with `this.lives = lives;` in the constructor body. What's actually different?
Nothing in access or runtime behavior. Both give the same private lives property. The shorthand is just a shorter way to write it.
Why doesn't marking every class property `private` reflexively make a class "safer" in every case?
If a property is meant to be read or set freely (a simple data holder with no rules), making it private only forces pointless getters and setters. It adds friction without preventing misuse.
When is `public` (the default) actually the right, deliberate choice rather than an oversight?
When the property has no rule to protect and is meant to be read or set from outside. Hiding it behind private plus getters just adds ceremony.
What mistake does using `protected` risk that using `private` wouldn't?
Any subclass, including ones written later by someone unfamiliar with the design, can depend on an internal detail that was never meant to be part of the contract.
A colleague uses `as any` to bypass a `private` field's type error and reads the value successfully at runtime. Does this reveal a flaw in TypeScript's `private`?
No, that's expected. private is compile-time only, so any code that gets past the type checker (a cast, or untyped JavaScript) can reach what is an ordinary property underneath.
The content notes JavaScript has its own native `#field` private syntax, calling it "unrelated" to TypeScript's `private` keyword. What's actually different about it?
TypeScript's private is a compile-time annotation; the compiled property is ordinary. JavaScript's #field is enforced by the engine at runtime: outside access is actually blocked, regardless of any type checking.
Untyped, plain JavaScript code calls into your compiled TypeScript class and directly reads a property you'd marked `private`. Does this throw at runtime?
No. private adds no runtime restriction, so plain JavaScript callers can read or write the property without error.
Why are access modifiers described as being about "guiding" other code toward intended public methods rather than about airtight runtime security?
The restriction only exists at compile time. It stops type-checked code from accidentally reaching in, but not determined or untyped code at runtime. It's a design tool, not a security boundary.
Given `class Cat { constructor(private lives: number = 9) {} loseLife(): number { return --this.lives; } }`, can code outside `Cat` call `cat.loseLife()`? Can it read `cat.lives` directly?
Yes to the first: loseLife has no modifier, so it's public. No to the second: lives is private through the shorthand, so cat.lives from outside is a compile error, even though the method that changes it is public.
If you wanted `lives` in the `Cat` example to be readable from outside but never directly writable, would `private` alone achieve that?
No. private blocks reading and writing from outside equally. Keep lives private and add a public getter method, the same pattern getBalance() uses in BankAccount.
Between the `BankAccount.balance` example and the `Cat.lives` example, what stays the same in terms of enforced access, and what differs?
Both are private and blocked from outside in the same way. Only the declaration differs: BankAccount uses a separate field plus an assignment in the constructor; Cat uses constructor-parameter shorthand.