
上QQ阅读APP看书,第一时间看更新
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.