Private Fields with Hash

JavaScript #private

#field is a JavaScript feature (ES2022). Unlike TypeScript private, it is enforced at runtime: code outside the class cannot read it even with tricks, and it does not show up in Object.keys or JSON.stringify.

Example

class ApiClient {
  #apiKey: string;
  private retries = 3;

  constructor(apiKey: string) {
    this.#apiKey = apiKey;
  }

  authHeader(): string {
    return "Bearer " + this.#apiKey.slice(0, 4) + "****";
  }
}

const client = new ApiClient("rzp_live_abc123");
console.log(client.authHeader());
console.log(JSON.stringify(client));             // retries visible, #apiKey not
console.log((client as any)["#apiKey"]);         // undefined at runtime

Output

Bearer rzp_****
{"retries":3}
undefined

Which One to Use

private x#x
Checked byTypeScript compiler onlyJavaScript runtime
Visible in JSON / consoleyesno
Works with parameter propertiesyesno
Common inAngular, NestJS serviceslibraries, security-sensitive code