官术网_书友最值得收藏!

Inheritance in TypeScript

We just saw how to implement an inheritance in JavaScript using a prototype. Now, we will see how an inheritance can be implemented in TypeScript, which is basically ES6 inheritance.

In TypeScript, similar to extending interfaces, we can also extend a class by inheriting another class, as follows:

class SimpleCalculator { 
   z: number; 
    constructor() { } 
   addition(x: number, y: number) { 
        this.z = this.x + this.y; 
   } 
    subtraction(x: number, y: number) { 
        this.z = this.x - this.y; 
   } 
} 
  
class ComplexCalculator extends SimpleCalculator { 
    constructor() { super(); } 
   multiplication(x: number, y: number) { 
        this.z = x * y; 
   } 
    division(x: number, y: number) { 
        this.z = x / y; 
   } 
} 
var calculator = new ComplexCalculator(); 
calculator.addition(10, 20); 
calculator.Substraction(20, 10); 
calculator.multiplication(10, 20); 
calculator.division(20, 10); 

Here, we are able to access the methods of SimpleCalculator using the instance of ComplexCalculator as it extends SimpleCalculator.

主站蜘蛛池模板: 长治市| 疏附县| 思南县| 中西区| 辽源市| 西峡县| 平乐县| 承德市| 孙吴县| 个旧市| 临夏市| 新营市| 龙岩市| 枞阳县| 昌乐县| 佳木斯市| 犍为县| 临猗县| 新乡县| 永泰县| 平度市| 贡嘎县| 宁远县| 吴旗县| 澎湖县| 山东省| 尉氏县| 六枝特区| 新邵县| 嘉祥县| 亚东县| 潢川县| 房山区| 梁平县| 兴安盟| 湘乡市| 高雄县| 灵丘县| 勃利县| 同仁县| 平泉县|