TypeScript Classes
TypeScript adds type safety to JavaScript classes — access modifiers (public, private, protected), parameter properties, abstract classes, and interface implementation. These features enable robust object-oriented design patterns.
40 min•By Priygop Team•Last updated: Feb 2026
Class Fundamentals
Example
// TypeScript class with access modifiers
class User {
readonly id: number; // Cannot change after construction
public name: string; // Accessible everywhere (default)
private password: string; // Only accessible inside this class
protected role: string; // Accessible inside and in subclasses
constructor(id: number, name: string, password: string, role: string = "user") {
this.id = id;
this.name = name;
this.password = password;
this.role = role;
}
// Public method
greet(): string {
return `Hi, I'm ${this.name}`;
}
// Private method
private hashPassword(): string {
return `hashed_${this.password}`;
}
// Protected method (accessible in subclasses)
protected getRole(): string {
return this.role;
}
}
// Parameter properties — shorthand
class Product {
constructor(
public readonly id: number,
public name: string,
public price: number,
private stock: number = 0
) {}
// Properties are automatically created from constructor params!
isInStock(): boolean {
return this.stock > 0;
}
}
// Getters and setters
class Temperature {
private _celsius: number;
constructor(celsius: number) {
this._celsius = celsius;
}
get fahrenheit(): number {
return this._celsius * 9 / 5 + 32;
}
set fahrenheit(f: number) {
this._celsius = (f - 32) * 5 / 9;
}
get celsius(): number {
return this._celsius;
}
}
const temp = new Temperature(100);
console.log(temp.fahrenheit); // 212
temp.fahrenheit = 32;
console.log(temp.celsius); // 0