Extending classes with class inheritance

Just like a class can be defined by an interface, it can also extend the members and functionality of other classes as if they were its own. We can make a class inherit from another by appending the keyword extends to the class name, including the name of the class we want to inherit its members from:

class Sedan extends Car {
model: string;
constructor(make: string, model: string) {
super(maker);
this.model = model;
}
}

Here, we extend from a parent class, Car, which already exposed a make member. We can populate the members already defined by the parent class and even execute their own constructor by executing the super() method, which points to the parent constructor. We can also override methods from the parent class by appending a method with the same name. Nevertheless, we will still be able to execute the original parent's class methods as it will be still accessible from the super object. Coming back to the interface, they can also inherit definition from other interfaces. Simply put, an interface can inherit from another interface.

As a word of caution, ES6 and TypeScript do not provide support for multiple inheritance. So, you may want to use composition or middleman classes instead, in case you want to borrow functionalities from different sources.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset