Careeroza
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 runtimeOutput
Bearer rzp_****
{"retries":3}
undefinedWhich One to Use
private x | #x | |
|---|---|---|
| Checked by | TypeScript compiler only | JavaScript runtime |
| Visible in JSON / console | yes | no |
| Works with parameter properties | yes | no |
| Common in | Angular, NestJS services | libraries, security-sensitive code |