Sub topic 17
ECMAScript `#private` fields
Assume you know basic TypeScript types, classes, constructors, and the this keyword. This chapter focuses on the difference between TypeScript's private modifier and JavaScript's runtime-enforced #private fields.
ECMAScript `#private` fields
A #private field is a class field whose name starts with #. Only the class that declares the field can read or change it. The JavaScript runtime enforces this rule after TypeScript has compiled the code.
class Counter {
private label: string;
#count = 0;
constructor(label: string) {
this.label = label;
}
increment(): void {
this.#count++;
}
describe(): string {
return `${this.label}: ${this.#count}`;
}
}
const counter = new Counter("requests");
counter.increment();
counter.increment();
console.log(counter.describe()); // requests: 2
// console.log(counter.#count); // Syntax error: private fields are inaccessible hereThe #count name is part of the JavaScript syntax. It is different from a normal string property named "#count":
console.log((counter as any)["#count"]); // undefinedBracket notation does not bypass the field. The private field has a separate internal identity.
A subclass cannot access a private field declared by its parent. A subclass must use a public or protected method supplied by the parent class. This separation prevents subclasses and outside code from depending on internal representation.
Compile-time versus runtime privacy
TypeScript's private modifier protects code while TypeScript checks it. The modifier is normally erased from emitted JavaScript. Runtime JavaScript can therefore access the resulting property if it knows its ordinary name.
The two forms differ in their protection and compatibility:
| Feature | TypeScript `private` | ECMAScript `#private` |
|---|---|---|
| Main protection | Compile time | Runtime and compile time |
| Bracket access after casting | Often possible | Does not reveal the field |
| JavaScript output | Ordinary property | Native private field or protected compiler output |
| Best use | Type-level API design | Runtime encapsulation |
class Example {
private typescriptValue = 1;
#runtimeValue = 2;
read(): [number, number] {
return [this.typescriptValue, this.#runtimeValue];
}
}
const example = new Example();
console.log((example as any).typescriptValue); // 1
console.log((example as any)["#runtimeValue"]); // undefinedType assertions such as as any silence the TypeScript checker. They do not create access to a #private field. Choose private when compile-time restrictions and simpler emitted objects are sufficient. Choose #private when the boundary must remain enforced at runtime.
Exercise
Which field should you choose when untrusted JavaScript must not access an object's internal value?
Show answer
Choose an ECMAScript #private field. TypeScript's private modifier alone does not enforce privacy at runtime.