Lesson 2 of 8
Access Modifiers - public, private, protected
Access modifiers control the visibility of class members. `public` is the default (always visible). `private` limits access to the declaring class. `protected` allows access in the declaring class AND subclasses. `readonly` prevents assignment after initialisation. Combining them produces precise APIs.
Access Modifiers - Full Visibility Rules
// ── Access modifier matrix ────────────────────────────────────
// | Declaring class | Subclass | Outside
// public | ✅ | ✅ | ✅
// protected | ✅ | ✅ | ❌
// private | ✅ | ❌ | ❌
// readonly | assign in constructor only, then immutable
class BaseRepository<T extends { id: number }> {
// private - only this class can access the store
private store = new Map<number, T>();
// protected - subclasses can build on this
protected findRaw(id: number): T | undefined {
return this.store.get(id);
}
// public API
findById(id: number): T | undefined {
return this.findRaw(id);
}
save(entity: T): T {
this.store.set(entity.id, entity);
return entity;
}
readonly size: number = 0; // TS readonly (not updated here - simplification)
}
class TaskRepository extends BaseRepository<Task> {
findByStatus(status: TaskStatus): Task[] {
// Can call protected method from parent:
// But cannot access private store directly (❌)
const all: Task[] = [];
for (let i = 0; i < /* hypothetical size */ 100; i++) {
const t = this.findRaw(i); // ✅ protected is accessible
if (t && t.status === status) all.push(t);
}
return all;
}
}
// ── TypeScript private vs JavaScript private fields ───────────
class SecureToken {
// TypeScript private - compile-time only, visible in JS output
private tsPrivate = "ts-secret";
// JavaScript private field (#) - RUNTIME enforced
#jsPrivate = "js-secret";
getTs(): string { return this.tsPrivate; }
getJs(): string { return this.#jsPrivate; }
}
const token = new SecureToken();
// (token as any).tsPrivate // ✅ bypasses TS, accessible at runtime!
// token.#jsPrivate // ❌ SyntaxError at runtime - truly privateCommon Mistakes
- Accessing `private` members via `as any` - if code needs a private member from outside, it's a design smell. Make the member `protected` or add a public accessor method instead.
- Assuming `protected` prevents misuse - `protected` only limits TYPESCRIPT callers. Subclasses can still misuse inherited state. Design the base class defensively.
- Using `readonly` on mutable objects - `readonly arr: string[]` prevents reassigning `arr`, but allows `arr.push()`. For a truly frozen array, use `readonly string[]` or `ReadonlyArray<string>`.
Tip
Tip
Practice Access Modifiers public private protected in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for Access Modifiers - public, private, protected
Practice Task
Note
Practice Task - (1) Write a working example of Access Modifiers public private protected from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Access Modifiers public private protected is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready typescript code.
Key Takeaways
- Access modifiers control the visibility of class members.
- Accessing `private` members via `as any` - if code needs a private member from outside, it's a design smell. Make the member `protected` or add a public accessor method instead.
- Assuming `protected` prevents misuse - `protected` only limits TYPESCRIPT callers. Subclasses can still misuse inherited state. Design the base class defensively.
- Using `readonly` on mutable objects - `readonly arr: string[]` prevents reassigning `arr`, but allows `arr.push()`. For a truly frozen array, use `readonly string[]` or `ReadonlyArray<string>`.
Finished this lesson?