DEV Community

Cover image for TypeScript `protected` vs `private` in 2026: The Inheritance Visibility Rules That Bite Teams Mid-Refactor
jsmanifest
jsmanifest

Posted on Originally published at jsmanifest.com

TypeScript `protected` vs `private` in 2026: The Inheritance Visibility Rules That Bite Teams Mid-Refactor

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

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

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

  • private members are invisible to subclasses; only the declaring class can access them, making them unsuitable for inheritance-based patterns.
  • protected members 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 private as a nominal constraint: two classes with identically named private fields are incompatible even if their shapes match.
  • Both private and protected disappear 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 public or 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
  }
}
Enter fullscreen mode Exit fullscreen mode

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;
  }
}
Enter fullscreen mode Exit fullscreen mode

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 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'
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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;
  }
}
Enter fullscreen mode Exit fullscreen mode

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;
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

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

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();
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

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();
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

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";
  }
}
Enter fullscreen mode Exit fullscreen mode

The TypeScript compiler targeting ES2015 emits:

class Secure {
  constructor() {
    this.secret = "hidden";
    this.internal = "shared";
    this.visible = "open";
  }
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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

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");
  }
}
Enter fullscreen mode Exit fullscreen mode

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);
  }
}
Enter fullscreen mode Exit fullscreen mode

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

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 protected. If the field exists only to support the base class's methods, make it private.

The exception: library code intended for public consumption. Public APIs often expose hooks (like React component lifecycle methods) but keep all state private. This prevents consumers from accidentally breaking the library's invariants. The library provides protected methods for subclass customization, but keeps data fields locked.

Migration Patterns: Fixing Mid-Refactor Visibility Violations Without Breaking Everything

Teams discover visibility violations mid-refactor when a subclass suddenly cannot access a field that was previously visible. The fix depends on whether the field should have been protected from the start, or whether the subclass access pattern was a mistake.

The first migration: promoting private to protected. This happens when a developer correctly identified shared state but chose the wrong modifier. The fix is mechanical: change private to protected in the base class. TypeScript recompiles without errors. Subclasses gain access:

// Before: private blocks subclass access
class EventEmitter {
  private listeners: Map<string, Function[]> = new Map();

  on(event: string, handler: Function) {
    const handlers = this.listeners.get(event) || [];
    handlers.push(handler);
    this.listeners.set(event, handlers);
  }
}

class LoggingEmitter extends EventEmitter {
  on(event: string, handler: Function) {
    console.log(`Registering ${event}`);
    // Need to access this.listeners but it's private
  }
}

// After: protected allows subclass access
class EventEmitter {
  protected listeners: Map<string, Function[]> = new Map();

  on(event: string, handler: Function) {
    const handlers = this.listeners.get(event) || [];
    handlers.push(handler);
    this.listeners.set(event, handlers);
  }
}

class LoggingEmitter extends EventEmitter {
  on(event: string, handler: Function) {
    console.log(`Registering ${event}`);
    const handlers = this.listeners.get(event) || []; // ✓ now allowed
    handlers.push(handler);
    this.listeners.set(event, handlers);
    super.on(event, handler);
  }
}
Enter fullscreen mode Exit fullscreen mode

The migration preserves the external API. Code that uses EventEmitter continues working. Only subclass implementations change.

The second migration: demoting protected to private with an accessor layer. This happens when subclass access was a mistake. The base class wants to change the field's implementation without breaking subclasses. The fix: add a protected getter/setter and mark the field private:

// Before: protected exposes implementation detail
class Cache {
  protected storage: Map<string, unknown> = new Map();

  get(key: string): unknown {
    return this.storage.get(key);
  }
}

class MetricsCache extends Cache {
  get(key: string): unknown {
    const value = this.storage.get(key); // direct access
    this.recordHit();
    return value;
  }
}

// After: private field with protected accessor
class Cache {
  private storage: Map<string, unknown> = new Map();

  protected getFromStorage(key: string): unknown {
    return this.storage.get(key);
  }

  get(key: string): unknown {
    return this.getFromStorage(key);
  }
}

class MetricsCache extends Cache {
  get(key: string): unknown {
    const value = this.getFromStorage(key); // accessor method
    this.recordHit();
    return value;
  }
}
Enter fullscreen mode Exit fullscreen mode

The base class can now replace storage (switching from Map to WeakMap, for example) without breaking subclasses. The protected accessor method abstracts the storage mechanism.

Migration flowchart for fixing visibility violations

Migration flowchart for fixing visibility violations

The third migration: extracting a new base class when visibility boundaries conflict. This happens when multiple subclasses need different access to the same field. The fix: create an intermediate base class with looser visibility, and derive restrictive subclasses from it:

// Problem: some subclasses need access, others don't
class Service {
  private connection: DatabaseConnection; // too restrictive
}

class AuditService extends Service {
  // Needs connection access but can't get it
}

class ReadOnlyService extends Service {
  // Doesn't need connection access
}

// Solution: intermediate base class with protected access
abstract class ConnectedService {
  protected connection: DatabaseConnection;

  constructor(conn: DatabaseConnection) {
    this.connection = conn;
  }
}

class AuditService extends ConnectedService {
  async log(event: string): Promise<void> {
    await this.connection.execute("INSERT INTO audit ..."); // ✓ allowed
  }
}

class ReadOnlyService extends ConnectedService {
  // Can access connection but chooses not to
}
Enter fullscreen mode Exit fullscreen mode

The intermediate class ConnectedService exposes the connection to its subclasses. Subclasses that need direct access derive from it. Subclasses that do not derive from a wrapper that hides it.

The key: migrate incrementally. Change one modifier at a time. Run the type checker after each change. Avoid bulk find-and-replace operations that change visibility across dozens of classes simultaneously. Each modifier change is a contract change. Subclasses may depend on the existing contract in subtle ways.

Frequently Asked Questions

Can a subclass override a private field from the base class?

No, subclasses cannot access private fields at all. TypeScript treats private as a strict boundary: only the declaring class can read or write the field. A subclass that declares a field with the same name creates a separate, unrelated field. The base class field remains hidden and inaccessible.

Does protected allow access from outside the inheritance chain?

No, protected members are visible only within the class and its subclasses. External code (code that does not extend the class) cannot access protected members. The visibility is strictly limited to the inheritance hierarchy, not to arbitrary code that imports the class.

Why does TypeScript reject assignment between structurally identical classes with private fields?

TypeScript uses nominal typing for private and protected members. Two classes with private fields of the same type and name are incompatible unless they share the same inheritance chain. This prevents accidental mixing of unrelated types that happen to have structurally similar private state.

Can I use protected in an interface?

No, TypeScript interfaces cannot declare protected members. Interfaces define public contracts for objects. Access modifiers like protected and private apply only to class declarations. If you need a contract that includes protected members, use an abstract class instead of an interface.

What happens to protected fields when compiling to JavaScript?

TypeScript strips all access modifiers during transpilation. A protected field becomes a regular public property in the emitted JavaScript. The runtime offers no enforcement. Any code can access the field using direct property access or bracket notation, regardless of the original TypeScript visibility.

Conclusion: Choosing the Right Access Modifier Before Your Team Hits the Wall

The difference between protected and private determines whether subclasses can access base class state. Choosing private locks the field to the declaring class. Choosing protected exposes it to the inheritance chain. Teams that understand this distinction before refactoring avoid mid-build visibility violations and the forced choice between leaky abstractions and redesigned hierarchies. The decision starts with one question: will subclasses need this field? The answer dictates the modifier.

Sources

Top comments (0)