{"id":4311,"date":"2022-09-30T17:40:14","date_gmt":"2022-09-30T22:40:14","guid":{"rendered":"https:\/\/www.becomebetterprogrammer.com\/?p=4311"},"modified":"2022-09-30T17:40:21","modified_gmt":"2022-09-30T22:40:21","slug":"typescript-extends","status":"publish","type":"post","link":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/typescript-extends\/","title":{"rendered":"TypeScript | A Practical Guide to Use Extends in TypeScript"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">With the introduction of&nbsp;<a href=\"https:\/\/www.ecma-international.org\/technical-committees\/tc39\/\" target=\"_blank\" rel=\"noreferrer noopener\">ECMAScript<\/a>&nbsp;2015, commonly known as ES6, you can implement object-oriented programming as a class-based approach in JavaScript\/TypeScript. Before that, JavaScript developers would use the prototype-based approach to implement the object-oriented pattern in their code. Similar to object-oriented languages like Java and C#, now TypeScript developers can use various object-oriented features like interfaces, inheritance, abstraction, and encapsulation as a class-based approach.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong><strong>The <code>extends<\/code> keyword in TypeScript is used to implement inheritance, a class-based object-oriented characteristic that lets the child class or the interface acquire the members from their parents. The <code>extends<\/code> keyword also comes in handy while performing abstraction, which uses inheritance.<\/strong><\/strong>\u00a0<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Inheritance is a mechanism where the child classes can access the properties and methods of the parent classes. Meanwhile, abstraction is a technique that hides the detailed code implementation from the user to reduce the complexity and increase efficiency.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The article will serve you as a practical guide on how to use <code>extends<\/code> keyword while implementing the different object-oriented characteristics like abstraction, inheritance, and encapsulation in TypeScript.<\/p>\n\n\n\n<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_85 counter-hierarchy ez-toc-counter ez-toc-custom ez-toc-container-direction\">\n<div class=\"ez-toc-title-container\"><p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<\/div><nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/typescript-extends\/#Using_extends_While_Implementing_Abstraction\" >Using extends While Implementing Abstraction<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/typescript-extends\/#Using_extends_with_Abstract_Class\" >Using extends with Abstract Class<\/a><ul class='ez-toc-list-level-4' ><li class='ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/typescript-extends\/#Creating_an_Abstract_Class\" >Creating an Abstract Class<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/typescript-extends\/#Extending_the_Abstract_Class\" >Extending the Abstract Class<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/typescript-extends\/#Using_extends_with_Interface\" >Using extends with Interface<\/a><ul class='ez-toc-list-level-4' ><li class='ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/typescript-extends\/#Creating_the_Interfaces\" >Creating the Interfaces<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/typescript-extends\/#Implementing_the_Interface\" >Implementing the Interface<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-8\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/typescript-extends\/#Extending_the_Multiple_Interfaces\" >Extending the Multiple Interfaces<\/a><\/li><\/ul><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-9\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/typescript-extends\/#Using_extends_While_Interface_Inherit_Classes\" >Using extends While Interface Inherit Classes<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-10\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/typescript-extends\/#Interface_Extending_a_Class\" >Interface Extending a Class<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-11\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/typescript-extends\/#Interface_Extending_Class_with_Private_Members_will_throw_an_error\" >Interface Extending Class with Private Members (will throw an error)<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-12\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/typescript-extends\/#Mistake_and_Correction_During_the_Implementation_of_the_Interface_While_Extending_Class\" >Mistake and Correction During the Implementation of the Interface While Extending Class<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-13\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/typescript-extends\/#The_Mistake\" >The Mistake<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-14\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/typescript-extends\/#The_Correction\" >The Correction<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-15\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/typescript-extends\/#Conclusion\" >Conclusion<\/a><\/li><\/ul><\/nav><\/div>\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Using_extends_While_Implementing_Abstraction\"><\/span>Using <code>extends<\/code> While Implementing Abstraction<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">In TypeScript, one can implement abstraction using either the abstract class or interfaces. During abstraction, a contract is created using either of these two methods. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A contract only contains the prototype, which the sub-classes must implement. In simpler terms, the prototypes are created in abstract class or the interface. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">These declarations must be implemented by the classes derived from the parent class or the interface.\u00a0<strong>The <code>extends<\/code> keyword makes the inheritance possible to achieve abstraction while using the abstract class. Likewise, the keyword is also functional when you need to extend an interface by another interface.<\/strong><\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Using_extends_with_Abstract_Class\"><\/span>Using <code>extends<\/code> with Abstract Class<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">You can apply the <code>abstract<\/code> keyword to both, the class and its members. <strong>The <code>extends<\/code> keyword comes into play while a sub-class inherits the abstract classes. The sub-class implements the abstract members defined in the abstract class.<\/strong> <\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Creating_an_Abstract_Class\"><\/span>Creating an Abstract Class<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">First, let&#8217;s create an abstract class <code>Student<\/code> as follows.<\/p>\n\n\n\n<pre class=\"wp-block-code language-typescript\"><code>abstract class Student {\n\n    name: string;\n    fee: number;\n\n    constructor(name: string, fee: number) {\n        this.name = name;\n        this.fee = fee;\n    }\n\n    public abstract cost(): number;\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">You just created an abstract class <code>Student<\/code> with properties <code>name<\/code> and <code>fee<\/code>. The constructor sets the value to the properties. There is an abstract method <code>cost()<\/code> that returns a number.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Now, let&#8217;s try to instantiate the abstract class and see what happens.<\/p>\n\n\n\n<pre class=\"wp-block-code language-typescript\"><code>let student = new Student('Subodh',10000)<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Oops! You get the following error.<\/p>\n\n\n\n<pre class=\"wp-block-code language-bash\"><code>Cannot create an instance of an abstract class.ts(2511)\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">You just learned something! <strong>You cannot instantiate an abstract class.<\/strong> The concept of abstract class is to provide abstraction, that is,  to define the prototypes which will be later implemented by sub-classes via inheritance. <strong>The <code>extends<\/code> keyword makes the inheritance possible<\/strong>.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Extending_the_Abstract_Class\"><\/span>Extending the Abstract Class<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Create a sub-class and inherit the abstract class using the <code>extends<\/code> keyword. You will implement the abstract method in the sub-class.<\/p>\n\n\n\n<pre class=\"wp-block-code language-typescript\"><code>abstract class Student {\n\n    name: string;\n    fee: number;\n\n    constructor(name: string, fee: number) {\n        this.name = name;\n        this.fee = fee;\n    }\n\n    public abstract cost(): number;\n}\n\nclass DomesticStudent extends Student {\n\n    constructor(name: string, fee: number) {\n        super(name, fee)\n    }\n\n    cost():number {\n        return this.fee;\n    }\n}\n\nclass InternationalStudent extends Student {\n    constructor(name: string, fee: number) {\n        super(name,fee)\n    }\n    cost():number {\n        return this.fee + 5000;\n    }\n}\n\nlet domesticStudent: Student = new DomesticStudent('jack',10000)\nlet internationalStudent: Student = new InternationalStudent('jim',10000)\n\nconsole.log(domesticStudent.cost()) \/\/ 10000\nconsole.log(internationalStudent.cost()) \/\/ 15000<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">In the above code snippet, there are two classes, <code>DomesticStudent<\/code> and <code>InternationalStudent<\/code>. These classes have inherited the abstract class <code>Student<\/code> using the <code>extends<\/code> keyword. Now, these classes can access the methods and properties of the <code>Student<\/code> class.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Inside each of these classes, there is a <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Classes\/constructor\" data-type=\"URL\" data-id=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Classes\/constructor\" target=\"_blank\" rel=\"noopener\">constructor<\/a> that has invoked the <code><a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Operators\/super\" target=\"_blank\" rel=\"noopener\">super()<\/a><\/code> expression. What <code>super()<\/code> does is it invokes the constructor of the parent class, which is the <code>Student<\/code> class&#8217; constructor. The <code>cost()<\/code> method is an abstract method that is implemented by both of the sub-classes. The method calculates the student&#8217;s fee according to the student type in both classes.<\/p>\n\n\n\n<p class=\"has-luminous-vivid-amber-background-color has-background wp-block-paragraph\"><strong>Note<\/strong>: The abstract members in the abstract class must be implemented by the classes that inherit the abstract class. Otherwise, an error will occur.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The above example demonstrated the use of the extends keyword in abstraction in TypeScript using the abstract class.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Using_extends_with_Interface\"><\/span>Using <code>extends<\/code> with Interface<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Interface in TypeScript has two purposes. One is to create the contract that the classes must implement. Another is to perform the type declaration, as&nbsp;<a href=\"https:\/\/www.typescriptlang.org\/\" target=\"_blank\" rel=\"noreferrer noopener\">TypeScript<\/a>&nbsp;is a strongly-typed language, a distinctive feature from JavaScript.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>The <code>extends<\/code> keyword makes the inheritance between interfaces functional<\/strong>.  In the example below,  you will learn how to use <code>extends<\/code> while performing inheritance among classes to achieve abstraction.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Creating_the_Interfaces\"><\/span>Creating the Interfaces<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">First, create an interface <code>RegularPhone<\/code> with the following properties and methods. Remember, you only need to set the rules in the interface. <\/p>\n\n\n\n<pre class=\"wp-block-code language-typescript\"><code>interface RegularPhone {\n    quantity: number;\n    price: number;  \n    cost(): number;\n  }<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Next, create another interface <code>ImportedPhone<\/code>  that extends the <code>RegularPhone<\/code> interface as follows.<\/p>\n\n\n\n<pre class=\"wp-block-code language-typescript\"><code>  interface ImportedPhone extends RegularPhone {\n    taxPercent: number;\n    taxAmount():number;  \n  }<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">You can see the use of the <code>extends<\/code> keyword while inheriting an interface by another interface. It means that the <code>ImportedPhone<\/code> interface can access the methods and properties defined in the <code>RegularPhone<\/code> interface.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Implementing_the_Interface\"><\/span>Implementing the Interface<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Now, let&#8217;s perform the implementation in  a class <code>Phone<\/code> as follows.<\/p>\n\n\n\n<pre class=\"wp-block-code language-typescript\"><code> class Phone implements ImportedPhone {\n    quantity: number;\n    price: number;\n    taxPercent: number;\n\n    constructor(quantity: number, price: number, taxPercent: number){\n        this.price = price;\n        this.quantity = quantity;\n        this.taxPercent= taxPercent;\n    }\n\n    taxAmount(): number{\n        return this.taxPercent \/ 100 * this.price\n    }\n\n    cost(): number{\n        if(this.taxAmount()!=0){\n            return (this.taxAmount() + this.price) * this.quantity\n        }\n        \n        return this.price*this.quantity\n        \n    }\n  }\n\nlet phone: Phone = new Phone(1,1000,15)\nlet phone1: Phone = new Phone(1,1000,0)\nconsole.log(phone.cost()) \/\/1150\nconsole.log(phone1.cost()) \/\/1000<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>Phone<\/code> class is an implementation of the contract in the <code>ImportedPhone<\/code> interface that you created above. The foremost thing you should do is implement all the properties and methods from the interface. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The properties <code>quantity<\/code> and <code>price<\/code> from the <code>RegularPhone<\/code> interface and <code>taxPercent<\/code> from the <code>importedPhone<\/code> interface are implemented in the class.  The constructor sets the values to these properties. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The next step is the implementation of the methods <code>cost()<\/code> and <code>taxAmount()<\/code>.  The <code>taxAmount()<\/code> method calculates the tax to be paid for a phone. Similarly, the  <code>cost()<\/code> method calculates the total cost of phones according to the tax. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Finally, the class <code>Phone<\/code> is instantiated and arguments are passed accordingly.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Thus, you used the <code>extends<\/code> keyword to implement the inheritance among the interfaces and achieved abstraction.<\/strong><\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Extending_the_Multiple_Interfaces\"><\/span>Extending the Multiple Interfaces<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>You can achieve the same goal as above(abstraction) by extending multiple interfaces by an interface. This technique is also known as <a href=\"https:\/\/en.wikipedia.org\/wiki\/Multiple_inheritance\" target=\"_blank\" rel=\"noopener\">multiple inheritance<\/a>.<\/strong> For example, create an interface <code>RegularPhone<\/code> and <code>ImportedPhone<\/code> as follows.<\/p>\n\n\n\n<pre class=\"wp-block-code language-typescript\"><code>interface RegularPhone {\n    quantity: number;\n    price: number;  \n  }\n\ninterface ImportedPhone {\n    taxPercent: number;\n  }<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Next, create another interface <code>PhoneInterface<\/code>, that uses the <code>extends<\/code> keyword to inherit these two interfaces, as shown  below.<\/p>\n\n\n\n<pre class=\"wp-block-code language-typescript\"><code>interface PhoneInterface extends RegularPhone, ImportedPhone{\n    cost(): number;\n  }<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Then, create a concrete class <code>Phone<\/code> that implements the <code>PhoneInterface<\/code>. The class must implement all the methods and properties of the interfaces.<\/p>\n\n\n\n<pre class=\"wp-block-code language-typescript\"><code>class Phone implements PhoneInterface {\n    quantity: number;\n    price: number;\n    taxPercent: number;\n\n    constructor(quantity: number, price: number, taxPercent: number){\n        this.price = price;\n        this.quantity = quantity;\n        this.taxPercent= taxPercent;\n    }\n\n    cost(): number{\n        if(this.taxPercent != 0){\n            let tax = this.taxPercent\/100 * this.price \n            return (tax+this.price)*this.quantity\n        }\n     return this.price*this.quantity   \n    }\n  }\n\nlet phone: Phone = new Phone(1,1000,15)\nlet phone1: Phone = new Phone(1,1000,0)\nconsole.log(phone.cost()) \/\/1150\nconsole.log(phone1.cost()) \/\/1000<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">In the concrete class, the constructor is used to set the values to properties, and the <code>cost()<\/code> method is implemented to calculate the phone cost.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>This way, you can achieve abstraction with multiple inheritance using the <code>extends<\/code> keyword with interface in TypeScript.<\/strong><\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Using_extends_While_Interface_Inherit_Classes\"><\/span>Using <code>extends<\/code> While Interface Inherit Classes<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>In TypeScript, interfaces can inherit classes using <code>extends<\/code>. It means that the interface can use the methods and properties of a class to create a prototype  but cannot implement those. <\/strong>The concrete class does the implementation.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Interface_Extending_a_Class\"><\/span>Interface Extending a Class<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Let&#8217;s see a quick example of an interface extending a class.<\/p>\n\n\n\n<pre class=\"wp-block-code language-typescript\"><code>class Vehicle {\n    name: string;\n    year: number;\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The class <code>Vehicle<\/code> contains the properties <code>name<\/code> and <code>year<\/code>. Remember that the properties are <code><a href=\"https:\/\/www.typescriptlang.org\/docs\/handbook\/2\/classes.html#public\" target=\"_blank\" rel=\"noopener\">public<\/a><\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Next, create an interface that extends the <code>Vehicle<\/code> class.<\/p>\n\n\n\n<pre class=\"wp-block-code language-typescript\"><code>\ninterface CarInterface extends Vehicle{\n    brandName: string;\n    display(): void;\n}\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>CarInterface<\/code> inherits the properties from the <code>Vehicle<\/code> class and  has a property <code>brandName<\/code> and a method <code>display()<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">To implement the <code>CarInterface<\/code>, create a concrete class <code>Car<\/code> as follows.<\/p>\n\n\n\n<pre class=\"wp-block-code language-typescript\"><code>class Car implements CarInterface {\n    brandName: string;\n    name: string;\n    year: number;\n\n    constructor(brandName: string, name: string, year: number){\n        this.brandName = brandName;\n        this.name= name;\n        this.year= year;\n\n    }\n\n    display():void {\n        console.log(`BrandName: ${this.brandName} Name: ${this.name} Year: ${this.year}`)\n    }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The class has implemented all the methods and properties from the <code>CarInterface<\/code>. Now, create an object of the class and call the  <code>display()<\/code>method as shown below.<\/p>\n\n\n\n<pre class=\"wp-block-code language-typescript\"><code>let car:Car = new Car('Toyota','Hilux',2022);\ncar.display() \/\/ BrandName: Toyota Name: Hilux Year: 2022<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The method displays the information about the car. The code execution is smooth.&nbsp;<strong>You just used <code>extends<\/code> to inherit the class by an interface.<\/strong><\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Interface_Extending_Class_with_Private_Members_will_throw_an_error\"><\/span>Interface Extending Class with Private Members (will throw an error)<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"> Now let&#8217;s perform a little tweak in the code. Set the access modifier <code><a href=\"https:\/\/www.typescriptlang.org\/docs\/handbook\/2\/classes.html#private\" target=\"_blank\" rel=\"noopener\">private<\/a><\/code> for the <code>year<\/code> property in the <code>Vehicle<\/code> class.<\/p>\n\n\n\n<pre class=\"wp-block-code language-typescript\"><code>class Vehicle {\n    name: string;\n    private year: number;\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Leave the  `CarInterface` interface as it is.<\/p>\n\n\n\n<pre class=\"wp-block-code language-typescript\"><code>interface CarInterface extends Vehicle{\n    brandName: string;\n    display(): void;\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">With the modification above, make sure you inherit the <code>Vehicle<\/code> class in the concrete class <code>Car<\/code> using <code>extends<\/code>. And do not forget to call the <code>super()<\/code> expression in the constructor. The <code>Car<\/code> class looks like this.<\/p>\n\n\n\n<pre class=\"wp-block-code language-typescript\"><code>class Car extends Vehicle implements CarInterface{\n    brandName: string;\n\n    constructor(brandName: string, name: string, year: number){\n        super()\n        this.brandName = brandName;\n        this.name= name;\n        this.year= year;\n\n    }\n\n    display():void {\n        console.log(`BrandName: ${this.brandName} Name: ${this.name} Year: ${this.year}`)\n    }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">When you try to run this code, it gives the following error.<\/p>\n\n\n\n<pre class=\"wp-block-code language-bash\"><code>Property 'year' is private and only accessible within class 'Vehicle'.ts(2341)<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The problem is you are trying to access the private property <code>year<\/code> of the <code>Vehicle<\/code> class from the <code>Car<\/code> class. In order to make this code work, you need to change the <code>private<\/code> access modifier to <code>protected<\/code> in the <code>Vehicle<\/code> class.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>The key takeaway is that the <code>protected<\/code> members can be accessed from sub-classes while the <code>private<\/code> members cannot.<\/strong><\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Mistake_and_Correction_During_the_Implementation_of_the_Interface_While_Extending_Class\"><\/span>Mistake and Correction During the Implementation of the Interface While Extending Class<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">There is yet another important point to note about interfaces extending classes. Whenever an interface extends a class with <strong>private or public members,<\/strong> then the implementation of the interface can only be done by the class or sub-class from which the interface was extended. Otherwise, the class cannot access those protected or private members.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">To validate it, look back to the <code>Car<\/code> class above (the first example). Though the class is not a sub-class of the <code>Vehicle<\/code> class, having the <code>public<\/code> members in the <code>Vehicle<\/code> class makes those members accessible from the <code>Car<\/code> class.  Thus, the interface implementation is possible in the sub-class. <\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"The_Mistake\"><\/span>The Mistake<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Let&#8217;s examine what happens when the interface is implemented when one of the <code>Vehicle<\/code> class members is <code><a href=\"https:\/\/www.typescriptlang.org\/docs\/handbook\/2\/classes.html#protected\" target=\"_blank\" rel=\"noopener\">protected<\/a><\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code language-typescript\"><code>class Vehicle {\n   name: string;\n   protected year: number;\n\n   constructor(name: string, year: number) {\r\n      this.name = name;\r\n      this.year = year;\r\n   }\n}\n\ninterface CarInterface extends Vehicle{\n    brandName: string;\n    display(): void;\n}\n\nclass Car implements CarInterface{\n    brandName: string;\n    name: string;\n    year: number;\n\n    constructor(brandName: string, name: string, year: number){\n        this.brandName = brandName;\n        this.name= name;\n        this.year= year;\n\n    }\n\n    display():void {\n        console.log(`BrandName: ${this.brandName} Name: ${this.name} Year: ${this.year}`)\n    }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Notice that the <code>year<\/code> property in the <code>Vehicle<\/code> class is <code>protected<\/code>, and the class <code>Car<\/code> only implements the <code>CarInterface<\/code> but does not extend the <code>Vehicle<\/code> base class.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The following error is encountered.<\/p>\n\n\n\n<pre class=\"wp-block-code language-bash\"><code>  Property 'year' is protected but type 'Car' is not a class derived from 'Vehicle'.ts(2420)\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The comprehensive error message makes it clear that in order to access the protected member, the <code>Car<\/code> class should inherit the <code>Vehicle<\/code> class. <\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"The_Correction\"><\/span>The Correction<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>The solution can be easily achieved by using the <code>extends<\/code> keyword in the class as follows.<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code language-typescript\"><code>class Car extends Vehicle implements CarInterface{\n    brandName: string;\n    name: string;\n    year: number;\n\n    constructor(brandName: string, name: string, year: number){\n        super()\n        this.brandName = brandName;\n        this.name= name;\n        this.year= year;\n\n    }\n\n    display():void {\n        console.log(`BrandName: ${this.brandName} Name: ${this.name} Year: ${this.year}`)\n    }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Also, do not miss the <code>super()<\/code> expression invocation as you inherit the base class from the sub-class.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Finally, create an object of the class and call the <code>display()<\/code> method.<\/p>\n\n\n\n<pre class=\"wp-block-code language-typescript\"><code>let car:Car = new Car('Toyota','Hilux',2022);\ncar.display() \/\/ BrandName: Toyota Name: Hilux Year: 2022<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Conclusion\"><\/span>Conclusion<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The article introduced and implemented the class-based object-oriented approach in TypeScript, mainly revolving around the concept of inheritance and abstraction. It demonstrated and depicted the essence of the <code>extends<\/code> keyword in such object-oriented practices in TypeScript. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You learned the various usages of the <code>extends<\/code> keyword including performing abstraction using abstract class and interfaces. Similarly, you also learned about inheritance and access modifiers while performing abstraction. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Was this article helpful for your learning process?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Feel free to share your thoughts by replying on <a href=\"http:\/\/twitter.com\/bbprogrammer\" target=\"_blank\" rel=\"noopener\">Twitter.<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>With the introduction of&nbsp;ECMAScript&nbsp;2015, commonly known as ES6, you can implement object-oriented programming as a class-based approach in JavaScript\/TypeScript. Before that, JavaScript developers would use the prototype-based approach to implement the object-oriented pattern in their code. Similar to object-oriented languages like Java and C#, now TypeScript developers can use various object-oriented features like interfaces, inheritance, &#8230; <a title=\"TypeScript | A Practical Guide to Use Extends in TypeScript\" class=\"read-more\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/typescript-extends\/\" aria-label=\"More on TypeScript | A Practical Guide to Use Extends in TypeScript\">Read more<\/a><\/p>\n","protected":false},"author":7,"featured_media":4402,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"nf_dc_page":"","_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[19],"tags":[],"class_list":["post-4311","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-typescript","generate-columns","tablet-grid-50","mobile-grid-100","grid-parent","grid-50"],"_links":{"self":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts\/4311","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/users\/7"}],"replies":[{"embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/comments?post=4311"}],"version-history":[{"count":5,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts\/4311\/revisions"}],"predecessor-version":[{"id":4401,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts\/4311\/revisions\/4401"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/media\/4402"}],"wp:attachment":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/media?parent=4311"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/categories?post=4311"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/tags?post=4311"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}