A private member is a class field or method whose name begins with `#`. Only the class that defines it can use that name. Use a private field when class methods need data that other code should not access directly. The `#` remains in the JavaScript code, so the runtime enforces the restriction. section 11.3.2 section 4.2.7
Keep a department field inside its class
In `src/index.ts`, `Employee` declares `#dept: string`, assigns it with `this.#dept = dept` in the constructor, and reads it with `this.#dept` in `writeDept()`. Calling `salesEmployee.writeDept()` prints `Fidel Vega works in Sales`. The `#` is required at declaration and at each access. section 11.3.2
Listing 11.9 Using a private field in the index.ts file in the src folder
type Person = {
id: string,
name: string,
city: string
};
class Employee {
public id: string;
public name: string;
#dept: string;
public city: string;
constructor(id: string, name: string, dept: string, city: string) {
this.id = id;
this.name = name;
this.#dept = dept;
this.city = city;
}
writeDept() {
console.log(`${this.name} works in ${this.#dept}`);
}
}
let salesEmployee = new Employee("fvega", "Fidel Vega", "Sales", "Paris");
salesEmployee.writeDept();
The complete `Employee` listing shows the field declaration, constructor assignment, and method access together. section 11.3.2
Private methods use the same notation: a class can call `this.#getDetail()`, but attempting `boots.#getDetail()` outside it produces a syntax error. This differs from an underscore name such as `_price`, which merely signals that callers should leave a property alone; it does not prevent access. section 4.2.7 section 3.5.3
Do not confuse `#dept` with TypeScript’s `private dept`. Both restrict access in TypeScript class code, but the `private` keyword’s protection is enforced by the compiler and absent from generated JavaScript. Choose `#` when the restriction must also hold at runtime. section 11.3.1 section 11.3.2











