Monday, December 3, 2018

Inheritance in Typescript



In TypeScript, you can inherit a class from another class. Just use the extends keyword to perform inheritance. Consider the following example to understand it better.
class Person {
// properties
firstName: string;
lastName: string;
// construtor
constructor (fName: string, lName: string) {
 // fill the properties
 this.firstName = fName;
 this.lastName = lName;
}
// method
getFullName() {
 return `${firstName} ${lastName}`;
}
}
class Employee extends Person {
// properties
empID: string;
designation: string;
// construtor
constructor (fName: string, lName: string,
eID: string, desig: string) {
 // call the base class constructor
 super(fName, lName);
 // fill the other properties
 this.empID = eID;
 this.designation = desig;
}
// method
getData() {
 return `${empID} - ${firstName} ${lastName}
=> ${designation}`;
}
}
Here the Employee class inherits its base Person by writing class Employee extends Person. In the derived class super(...) is compulsory to call the constructor of the base class. For example, super(fName, lName) in Employee class constructor calls the base class constructor by passing the parameter values fName and lName.
let employee: Employee = new Employee ("Kunal",
                                     "Chowdhury",
                                     "EMP001022",
                                     "Software Engineer"
                                    );

console.log(employee.getData());

No comments:

Followers

Link