Private Class Members
What
Private class members are properties or methods that cannot be accessed or modified from outside the class where they are defined.
How
TypeScript supports the native JavaScript # syntax for private members. These fields are truly private at both compile-time and runtime:
class SecretAgent {
#id: string; // Private field
constructor(id: string) {
this.#id = id;
}
getId() {
return this.#id; // OK: Access within class
}
}
const bond = new SecretAgent("007");
// Error: Property '#id' is not accessible outside class
console.log(bond.#id);
Why
Using private fields allows you to encapsulate the internal state of your objects, preventing external code from creating invalid states or relying on implementation details that might change later.
Summary
The # syntax is the standard, native way to ensure data privacy in your classes.