TypeScript classes bring object-oriented programming to JavaScript with a type-safe twist. You get `public`, `private`, and `protected` modifiers to control access to properties and methods. Constructors initialize your class instances, and you can leverage inheritance to build complex hierarchies while maintaining type safety throughout.
Class Features
Classes in TypeScript are essentially typed JavaScript classes with additional type safety. You can define properties with access modifiers, implement interfaces, use inheritance, and benefit from static properties that belong to the class itself. All this while keeping the familiar JavaScript syntax you know and love.
class User {
private id: number;
protected name: string;
public email: string;
constructor(id: number, name: string, email: string) {
this.id = id;
this.name = name;
this.email = email;
}
getUserId(): number {
return this.id;
}
greet(): string {
return `Hello, ${this.name}!`;
}
}
class AdminUser extends User {
private permissions: string[];
constructor(id: number, name: string, email: string, permissions: string[]) {
super(id, name, email);
this.permissions = permissions;
}
hasPermission(action: string): boolean {
return this.permissions.includes(action);
}
}
const admin = new AdminUser(1, "Bob", "bob@example.com", ["read", "write", "delete"]);
Try it Yourself โ