Typescript - Human Inheritance

TypeScript - JavaScript's Superset (Article) (Program)

107

Typescript Human Inheritance

Create class "Human" which has two protected members:

⚫ name[type as string] and age[type as number]

⚫ constructor(): this initialises name and age.

⚫ Create another class "Employee" which extends "Human" and have three members:

⚫ department[type as string], batch[type as string] and role[type as string]

⚫ constructor(): this initialises parent class protected members, department, batch and role.

⚫ getInfo(): this dispalys name, age, department, batch and role of the employee in a specific format.

Given Input:


Expected Output:

Name: person one
Age: 21
Department: computer science
Batch: 2019
Role: Trainee

Program:

class Human {
  protected name: string;
  protected age: number;

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

class Employee extends Human {
  private department: string;
  private batch: string;
  private role: string;

  constructor(name: string, age: number, department: string, batch: string, role: string) {
    super(name, age);
    this.department = department;
    this.batch = batch;
    this.role = role;
  }

  getInfo(): void {
    console.log(`Name: ${this.name}`);
    console.log(`Age: ${this.age}`);
    console.log(`Department: ${this.department}`);
    console.log(`Batch: ${this.batch}`);
    console.log(`Role: ${this.role}`);
  }
}

// Example usage:
const employee = new Employee("person one", 21, "Computer Science", "2019", "Trainee");
employee.getInfo();

Output:

// Example usage:
const employee = new Employee("person one", 21, "Computer Science", "2019", "Trainee");
employee.getInfo();