Object-Oriented TypeScript

Lesson 7: Classes in TypeScript

Build organized and reusable object-oriented programs using classes, constructors, methods, access modifiers, and inheritance.

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

  • public members are accessible everywhere.
  • private members are accessible only inside the class.
  • protected members 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.