JavaScript (ES2022+) supports private fields using #
syntax. TypeScript provides private
, protected
, and public
modifiers.
Public (Default)
class User {
public username: string;
constructor(username: string) {
this.username = username;
}
}
const user = new User("Alice");
console.log(user.username); // Alice
Private (private
in TypeScript, #
in JavaScript)
class Employee {
#salary: number;
private tsPrivate = "TS private"; // TypeScript only
constructor(salary: number) {
this.#salary = salary;
}
getSalary() {
return this.#salary;
}
}
const emp = new Employee(5000);
console.log(emp.getSalary()); // ✅ 5000
// console.log(emp.#salary); // JS error: Cannot access private field
// console.log(emp.tsPrivate); // TS error, but still accessible in JS
Protected (protected
in TypeScript)
class Vehicle {
protected speed: number;
constructor(speed: number) {
this.speed = speed;
}
}
class Car extends Vehicle {
accelerate() {
this.speed += 10;
console.log(`Accelerated to ${this.speed} km/h`);
}
}
const car = new Car(50);
car.accelerate(); // Accelerated to 60 km/h
// console.log(car.speed); // Error: 'speed' is protected
Getters (get
) and setters (set
) allow controlled access to class properties.
class Person {
private _age: number;
constructor(age: number) {
this._age = age;
}
get age() {
return this._age;
}
set age(value: number) {
if (value < 0) throw new Error("Age must be positive.");
this._age = value;
}
}
const person = new Person(25);
console.log(person.age); // 25
person.age = 30;
console.log(person.age); // 30
Computed Property Example
class Rectangle {
constructor(private width: number, private height: number) {}
get area() {
return this.width * this.height;
}
}
const rect = new Rectangle(10, 5);
console.log(rect.area); // 50