Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

A private getter in TypeScript is an accessor method restricted by a private access modifier, confining its invocation strictly to the lexical scope of the declaring class. It encapsulates property retrieval logic while preventing access from class instances, external modules, or derived subclasses. TypeScript supports two distinct syntaxes for implementing private getters, differing primarily in their compilation and runtime behavior.

TypeScript private Keyword (Compile-Time Privacy)

Using the private keyword enforces visibility strictly during the TypeScript compilation phase. At runtime, the compiled JavaScript exposes the getter on the prototype, making it technically accessible if type-checking is bypassed.
class SoftPrivate {
  private _baseMultiplier: number = 10;

  // Compile-time private getter
  private get multiplier(): number {
    return this._baseMultiplier;
  }

  public calculate(value: number): number {
    // Valid: Accessed within the declaring class
    return value * this.multiplier;
  }
}

const instance = new SoftPrivate();
// instance.multiplier; // TypeScript Error: Property 'multiplier' is private and only accessible within class 'SoftPrivate'.

ECMAScript # Identifier (Runtime Privacy)

Using the ECMAScript # prefix creates a hard private getter. This enforces strict encapsulation at both compile-time and runtime, ensuring the getter cannot be accessed or inspected outside the class via JavaScript reflection or prototype manipulation.
class HardPrivate {
  #baseMultiplier: number = 10;

  // Runtime and compile-time private getter
  get #multiplier(): number {
    return this.#baseMultiplier;
  }

  public calculate(value: number): number {
    // Valid: Accessed within the declaring class
    return value * this.#multiplier;
  }
}

const instance = new HardPrivate();
// instance.#multiplier; // Syntax Error: Property '#multiplier' is not accessible outside class 'HardPrivate' because it has a private identifier.

Key Characteristics

  • Read-Only Nature: A private getter without a corresponding private setter creates a strictly read-only property within the class context. Attempting to assign a value to it internally will result in a compiler error.
  • Subclass Restriction: Unlike the protected modifier, neither private nor # getters can be accessed by classes extending the base class.
  • Memory Allocation: Standard getters are defined on the class prototype. However, ECMAScript private getters (#) utilize internal slots or WeakMap implementations under the hood in the JavaScript engine to guarantee runtime privacy, meaning they are not enumerable or accessible via Object.getPrototypeOf().
Master TypeScript with Deep Grasping Methodology!Learn More