TypeScript Class Definition and Inheritance

TypeScript is a statically typed programming language that is a superset of JavaScript. Therefore, it can use all features of JavaScript while also providing additional language features, including classes and objects.

A class is a concept in object-oriented programming; it is a structured data type that defines the attributes and methods of an object. In TypeScript, a class can be defined using the class keyword, for example:

class Person {
  private name: string;
  private age: number;
  
  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }
  
  public sayHello(): void {
    console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
  }
}

The code above defines a class named Person with two private attributes (name and age), a constructor, and a public method sayHello. The constructor is used to initialize the class's attributes when an object is created, while the sayHello method is used to print the attribute values of the object.

An object is an instance of a class; it is the concretization of the class and possesses the attributes and methods defined within the class. In TypeScript, instances of a class can be created using the new keyword, for example:

const person = new Person("Alice", 30);
person.sayHello(); // Outputs "Hello, my name is Alice and I am 30 years old."

The code above creates an instance of the Person class named person and calls its sayHello method. The output is "Hello, my name is Alice and I am 30 years old.".

In TypeScript, a class can inherit from another class, meaning one class can use the attributes and methods of another. Inheritance uses the extends keyword, for example:

class Employee extends Person {
  private salary: number;
  
  constructor(name: string, age: number, salary: number) {
    super(name, age);
    this.salary = salary;
  }
  
  public saySalary(): void {
    console.log(`My salary is ${this.salary} dollars.`);
  }
}

The code above defines a class named Employee that inherits from the Person class. It adds a private attribute named salary and a public method named saySalary. In its constructor, it initializes the name and age attributes by calling the parent class's constructor and initializes its own salary attribute.

Instances of the Employee class can be created in the same way as instances of the Person class, and their methods can be called. Since the Employee class inherits from the Person class, instances of the Employee class can also call methods defined in the Person class.