TypeScript protected vs private in 2026: The Inheritance Visibility Rules That Bite Teams Mid-Refactor
This article was written with the assistance of AI, under human supervision and review.
The Access Modifier Confusion That Breaks Refactors
Teams discover the difference between protected and private when a seemingly safe refactor suddenly fails type checking. A developer extracts shared logic into a base class, marks a field private, and watches the entire subclass hierarchy reject access to that field. The build breaks. The refactor stalls. The team backtracks to public and ships the leaky abstraction.
The problem: private members vanish the moment inheritance enters the picture. Subclasses cannot touch them. The TypeScript compiler enforces this boundary strictly, treating private as a hard contract between the declaring class and no one else. When developers expect inheritance-friendly visibility, they reach for the wrong modifier and hit a wall mid-refactor.
Problem diagram showing private field blocking subclass access
The solution: protected members expose themselves to the inheritance chain. Subclasses gain access. The refactor proceeds without visibility violations. The type checker passes because the modifier matches the actual access pattern.
Solution diagram showing protected field allowing subclass access
This matters because the wrong choice compounds during maintenance. A private field that should have been protected forces awkward workarounds (public getters, reflection tricks, or abandoning inheritance entirely). Teams that understand the visibility rules ship cleaner hierarchies and avoid the mid-refactor panic when TypeScript refuses to compile.
Key Takeaways
-
privatemembers are invisible to subclasses; only the declaring class can access them, making them unsuitable for inheritance-based patterns. -
protectedmembers expose themselves to the entire inheritance chain, allowing subclasses to access and override them while still hiding them from external code. - TypeScript's structural typing treats
privateas a nominal constraint: two classes with identically namedprivatefields are incompatible even if their shapes match. - Both
privateandprotecteddisappear during compilation to JavaScript; the runtime offers zero enforcement, making these purely compile-time contracts. - Choosing the wrong modifier mid-refactor forces visibility violations that break builds and require either exposing fields as
publicor redesigning the hierarchy.
How protected and private Actually Work: The Visibility Rules
TypeScript's access modifiers control compile-time visibility, not runtime behavior. The TypeScript handbook defines three visibility levels: public (accessible everywhere, the default), protected (accessible within the class and its subclasses), and private (accessible only within the declaring class). These boundaries exist solely during type checking.
A private member creates a one-class perimeter. The declaring class can read and write it. Subclasses cannot. External code cannot. The TypeScript compiler enforces this by rejecting any access outside the declaring class:
class DatabaseConnection { private credentials: string; constructor(creds: string) { this.credentials = creds; // ✓ allowed in declaring class } connect() { console.log(`Connecting with ${this.credentials}`); } } class SecureConnection extends DatabaseConnection { audit() { console.log(this.credentials); // ✗ Property 'credentials' is private } } The subclass SecureConnection inherits the structure of DatabaseConnection, but the private modifier blocks access. The compiler sees the reference to this.credentials and rejects it. The error message is explicit: Property 'credentials' is private and only accessible within class 'DatabaseConnection'.
A protected member expands the perimeter to include the inheritance chain. The declaring class and all subclasses can access it. External code still cannot. This matches the common pattern where base classes define fields that subclasses need to implement specialized behavior:
class Cache { protected storage: Map<string, unknown>; constructor() { this.storage = new Map(); // ✓ allowed in declaring class } get(key: string): unknown { return this.storage.get(key); // ✓ allowed in declaring class } } class LRUCache extends Cache { private accessOrder: string[] = []; get(key: string): unknown { const value = this.storage.get(key); // ✓ allowed in subclass this.accessOrder.push(key); return value; } } The protected field storage is visible to both Cache and LRUCache. The subclass can directly read the map to implement custom eviction logic. The external API remains unchanged because protected still hides the field from consumers of the class.
TypeScript visibility diagram showing access modifier boundaries
TypeScript does not allow cross-hierarchy protected access. A subclass can access protected members on this, but not on sibling class instances. This prevents a Derived1 instance from reaching into a Derived2 instance's protected state, even though both extend the same base class. The TypeScript handbook explains this as a safeguard against unintended coupling between unrelated subclasses.
The visibility rules create a hierarchy of access: private locks the field to one class, protected extends visibility to descendants, and public removes restrictions entirely. Developers choose based on how the field participates in inheritance.
The Structural Typing Trap: Why private Members Break Type Compatibility
TypeScript uses structural typing for most type checks. Two objects with identical shapes are compatible, regardless of where they were declared. The compiler compares properties, not names or origins. A { x: number } from one file matches a { x: number } from another.
private and protected members break this rule. The TypeScript compiler treats them nominally: two types are compatible only if their private or protected members come from the same declaration. The TypeScript handbook states this explicitly: "For two types to be considered compatible, if one of them has a private member, then the other must have a private member that originated in the same declaration."
This creates surprising incompatibility between structurally identical classes:
class Animal { private name: string; constructor(name: string) { this.name = name; } } class Employee { private name: string; constructor(name: string) { this.name = name; } } const animal: Animal = new Animal("Dog"); const employee: Employee = new Employee("Alice"); const entity: Animal = employee; // ✗ Type 'Employee' is not assignable to type 'Animal' Both Animal and Employee have a private name: string field. The shapes are identical. Structural typing would treat them as compatible. The compiler rejects the assignment because the private members originated in different declarations. The name in Animal and the name in Employee are distinct, incompatible types.
Inheritance preserves the declaration origin. A subclass that extends a base class inherits the base's private and protected members, including their declaration origin. This makes the subclass compatible with the base:
class Animal { private name: string; constructor(name: string) { this.name = name; } } class Dog extends Animal { constructor(name: string) { super(name); } } const animal: Animal = new Dog("Rex"); // ✓ compatible via inheritance The private name in Dog originated in Animal. The compiler sees the shared origin and allows the assignment. This nominal check ensures that private members remain truly private: only classes in the same inheritance chain can share them.
This matters during refactors. Extracting a base class with private fields breaks compatibility with any external code that expects the original type. The structural shape remains identical, but the declaration origin changes. Type checks that previously passed now fail.
The workaround: use protected for fields that participate in inheritance, or avoid access modifiers entirely for fields that need structural compatibility.
protected vs private in Inheritance Hierarchies: Real Refactoring Scenarios
Teams hit the protected versus private decision when pulling shared state into a base class. The question: should subclasses access this field directly, or only through methods?
A common scenario: multiple service classes share database connection logic. The initial implementation duplicates the connection field in each class. The refactor extracts a BaseService with the shared connection. The developer marks it private to enforce encapsulation:
class BaseService { private connection: DatabaseConnection; constructor(conn: DatabaseConnection) { this.connection = conn; } protected query(sql: string): Promise<unknown[]> { return this.connection.execute(sql); } } class UserService extends BaseService { async findById(id: number): Promise<User | null> { // Must use this.query() instead of direct connection access const rows = await this.query(`SELECT * FROM users WHERE id = ${id}`); return rows[0] as User; } } The private connection forces subclasses to use the protected query() method. This works when the base class API covers all use cases. It breaks when a subclass needs direct connection access for transaction management, connection pooling, or custom query building. The refactor stalls. The developer either exposes connection as public (leaking the abstraction) or redesigns the base class API to support every possible use case (overengineering).
The alternative: mark connection as protected. Subclasses gain direct access. The base class still hides it from external code:
class BaseService { protected connection: DatabaseConnection; constructor(conn: DatabaseConnection) { this.connection = conn; } } class TransactionalUserService extends BaseService { async createWithAudit(user: User): Promise<void> { const tx = await this.connection.beginTransaction(); // ✓ direct access try { await tx.execute("INSERT INTO users ..."); await tx.execute("INSERT INTO audit_log ..."); await tx.commit(); } catch (error) { await tx.rollback(); throw error; } } } The subclass uses the connection directly for transaction control. The base class does not need to anticipate every transaction pattern. The protected modifier trusts subclasses to use the connection correctly.
Inheritance hierarchy showing protected field access patterns
Another scenario: a Component base class manages lifecycle state. Subclasses need to read the current state to decide whether to run certain logic. The developer marks state private and adds a getter:
class Component { private state: "mounted" | "unmounted" = "unmounted"; mount() { this.state = "mounted"; this.onMount(); } protected onMount() { // hook for subclasses } isMounted(): boolean { return this.state === "mounted"; } } class AsyncComponent extends Component { protected onMount() { if (this.isMounted()) { // must call getter this.loadData(); } } } The getter works, but adds indirection. Every subclass that checks state calls isMounted() instead of reading state directly. If the state shape becomes more complex (adding "mounting", "unmounting", "error" states), the base class must add corresponding getters for each state. This scales poorly.
The protected alternative eliminates the getter:
class Component { protected state: "mounted" | "unmounted" = "unmounted"; mount() { this.state = "mounted"; this.onMount(); } protected onMount() {} } class AsyncComponent extends Component { protected onMount() { if (this.state === "mounted") { // direct access this.loadData(); } } } Subclasses read state directly. The base class does not proliferate getters. The tradeoff: subclasses can mutate state incorrectly. The developer trusts that subclass authors understand the lifecycle contract.
Runtime Reality: Why Both Modifiers Disappear in Compiled JavaScript
TypeScript's access modifiers exist only during type checking. The compiler strips them during transpilation. The emitted JavaScript contains no enforcement, no runtime checks, and no access restrictions. A private field becomes an ordinary property accessible via bracket notation or reflection.
The TypeScript handbook states this explicitly: "Like other aspects of TypeScript's type system, private and protected are only enforced during type checking." The compiled output looks identical for public, protected, and private fields.
class Secure { private secret: string; protected internal: string; public visible: string; constructor() { this.secret = "hidden"; this.internal = "shared"; this.visible = "open"; } } The TypeScript compiler targeting ES2015 emits:
class Secure { constructor() { this.secret = "hidden"; this.internal = "shared"; this.visible = "open"; } } All three fields appear as regular properties. No visibility enforcement. A consumer can access secret and internal directly:
const instance = new Secure(); console.log(instance.secret); // "hidden" — no runtime error console.log(instance["secret"]); // "hidden" — bracket notation bypasses TypeScript The TypeScript compiler rejects these accesses during type checking, but the runtime allows them. This creates a disconnect: code that fails to compile still runs successfully if the type checks are bypassed.
JavaScript's #private syntax (standardized in ES2022) provides runtime enforcement. Fields declared with # are truly private: the JavaScript engine prevents external access:
class Secure { #secret = "hidden"; getSecret() { return this.#secret; // ✓ internal access allowed } } const instance = new Secure(); console.log(instance.#secret); // SyntaxError: Private field '#secret' must be declared The # syntax creates hard privacy. The engine throws an error at runtime, not just during compilation. TypeScript supports this syntax and treats #private fields as truly inaccessible.
| Feature | TypeScript private | TypeScript protected | JavaScript #private |
|---|---|---|---|
| Compile-time enforcement | Yes (TypeScript only) | Yes (TypeScript only) | Yes (TypeScript only) |
| Runtime enforcement | No | No | Yes (JavaScript engine) |
| Subclass access | Blocked | Allowed | Blocked |
| External access via bracket notation | Allowed at runtime | Allowed at runtime | Blocked |
| Transpilation to ES5 | Becomes public property | Becomes public property | Polyfilled with WeakMap |
Comparison diagram showing TypeScript private versus JavaScript private fields
Teams that need runtime privacy use #private fields. Teams that need inheritance-friendly visibility use protected. Teams that want compile-time guardrails without runtime overhead stick with TypeScript's private and accept the soft enforcement.
The practical implication: access modifiers are documentation for the type checker and other developers. They communicate intent (this field should not leak outside the class), but they do not prevent malicious or careless access at runtime. Security-critical code requires additional runtime validation.
When to Reach for protected vs private: Decision Framework for 2026
The choice between protected and private depends on whether subclasses need field access. The decision tree starts with one question: will any subclass need to read or write this field directly?
If no subclass needs access, use private. This signals that the field is an implementation detail of the declaring class. Subclasses should not depend on it. Future refactors can change the field's type, name, or behavior without breaking subclasses:
class HttpClient { private retryCount: number = 0; private maxRetries: number = 3; async request(url: string): Promise<Response> { while (this.retryCount < this.maxRetries) { try { return await fetch(url); } catch (error) { this.retryCount++; } } throw new Error("Max retries exceeded"); } } The retryCount and maxRetries fields manage retry logic internal to HttpClient. No subclass needs to know about them. Marking them private allows the developer to replace the retry mechanism (switching to exponential backoff, for example) without touching subclass code.
If subclasses need access, use protected. This signals that the field participates in the inheritance contract. Subclasses can read and write it to implement specialized behavior:
class Repository { protected cache: Map<string, unknown> = new Map(); get(key: string): unknown | undefined { return this.cache.get(key); } set(key: string, value: unknown): void { this.cache.set(key, value); } } class TTLRepository extends Repository { private expirations: Map<string, number> = new Map(); set(key: string, value: unknown, ttl: number): void { this.cache.set(key, value); // ✓ direct cache access this.expirations.set(key, Date.now() + ttl); } get(key: string): unknown | undefined { const expiration = this.expirations.get(key); if (expiration && Date.now() > expiration) { this.cache.delete(key); // ✓ direct cache access this.expirations.delete(key); return undefined; } return this.cache.get(key); } } The protected cache allows TTLRepository to implement expiration logic without duplicating the storage mechanism. The base class trusts subclasses to maintain cache consistency.
| Scenario | Use private | Use protected |
|---|---|---|
| Field is pure implementation detail | ✓ | |
| Subclasses will never need access | ✓ | |
| Field participates in overridable behavior | ✓ | |
| Subclasses need direct read/write access | ✓ | |
| Future subclasses are unknown but likely | ✓ | |
| Field type may change in future versions | ✓ |
Decision flowchart for choosing between protected and private
A common pattern: use private for fields that drive internal algorithms, and protected for fields that represent shared state. If the field's value affects how subclasses implement their behavior, make it prot...





