Private Fields
The difference between TypeScript private fields and ECMAScript
TypeScript private is erased at compile time. ECMAScript #private fields are enforced by JavaScript at runtime.
Use #private when outside code must not read a field, even through casts or reflection-style access.
class SecureConfig {
readonly name: string;
#apiKey: string;
constructor(name: string, apiKey: string) {
this.name = name;
this.#apiKey = apiKey;
}
makeRequest(endpoint: string): string {
return `${endpoint}?key=${this.#apiKey}`;
}
}
const config = new SecureConfig("prod", "secret-key-123");
console.log(config.name);
// console.log(config.#apiKey); // syntax error outside the classIn production
TypeScript private is fine for normal internal APIs. Use #private for
runtime privacy, such as secrets that should not appear during object walking,
serialization, or casual debugging.
Enjoyed this? Get more software craft delivered to your inbox.