Creating a Class
class Student {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
showInfo(): void {
console.log(this.name + " is " + this.age + " years old.");
}
}
Access Modifiers
publicmembers are accessible everywhere.privatemembers are accessible only inside the class.protectedmembers are accessible in the class and its subclasses.
Inheritance
class Person {
constructor(public name: string) {}
}
class Teacher extends Person {
constructor(name: string, public subject: string) {
super(name);
}
}
Inheritance allows one class to reuse and extend another class.
Best practice: Keep each class focused on one responsibility so the code stays easy to understand and maintain.
Summary
Classes allow you to group data and behavior together. TypeScript improves classes with strong typing, access modifiers, and better structure for larger projects.