TypeScript brings full object-oriented programming (OOP) capabilities to JavaScript classes, adding access modifiers (public, private, protected), readonly fields, parameter properties, abstract classes, and interface implementation.
public: Accessible from anywhere (default).private (# or private): Accessible only within the declaring class.protected: Accessible within the declaring class and its subclasses.readonly: Field can only be assigned during declaration or inside the constructor.interface Printable {
printSummary(): void;
}
abstract class BaseEntity {
constructor(public readonly id: string, public readonly createdAt: Date) {}
abstract getEntityType(): string;
}
class UserAccount extends BaseEntity implements Printable {
private _hashedPasswordHash: string;
protected loginCount: number = 0;
// Parameter Properties shortcut in constructor
constructor(
id: string,
public username: string,
public email: string,
passwordHash: string
) {
super(id, new Date());
this._hashedPasswordHash = passwordHash;
}
public getEntityType(): string {
return "UserAccount";
}
public recordLogin(): void {
this.loginCount++;
console.log(`User ${this.username} logged in. Total logins: ${this.loginCount}`);
}
public printSummary(): void {
console.log(`[${this.getEntityType()}] ID: ${this.id} | User: ${this.username} (${this.email})`);
}
}
const user = new UserAccount("usr_001", "alice_dev", "[email protected]", "secret_hash");
user.recordLogin();
user.printSummary();
constructor(public name: string) eliminates redundant class field assignments.#field for True Enclosure: TypeScript private keyword is stripped at compile-time, while ES #field enforces runtime privacy.abstract Classes for Framework Blueprints: Define common base logic while enforcing abstract method overrides in derived classes.Create a class Car with a private field speed and a public method accelerate(amount: number).
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With