theory.ts

Classes & Object-Oriented Programming

Class Fundamentals

Classes in TypeScript define blueprints for creating objects with properties and methods.

  • A class can contain properties and methods.
  • Constructors initialise object properties when an instance is created.
  • The `this` keyword refers to the instance of the class.
// Defining a class with properties and methods
class Person {
  name: string;
  age: number;

  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }

  greet() {
    return `Hello, my name is ${this.name}.`;
  }
}

// Creating an instance of the class
const person1 = new Person("Alice", 30);
console.log(person1.greet()); // "Hello, my name is Alice."