Class inheritance and interface implementation

Just like in .NET, TypeScript classes can inherit from only one class, but can implement as many interfaces as desired.

Inheritance is defined by using the extends keyword, while interface implementation uses the implements keyword, as follows:

interface Calculator {
calc(left: number, right: number): number;
}

interface Printable {
print();
}

class HistoryCalculator {
protected history = [];
protected logHistory() {
console.log(`current history length: ${this.history.length}`);
}
}

class SumCalculator extends HistoryCalculator implements Calculator, Printable {
calc(left: number, right: number): number {
this.history.push({left, right});
return left + right;
}

print() {
this.logHistory();
}
}

const calc = new SumCalculator();
console.log(calc.calc(2,3));
calc.print();

In the preceding example, two interfaces are defined: Calculator with a calc function and Printable with a print function.

Then, a class called HistoryCalculator is defined that states that other calculator classes can derive from and get this specific history implementation.

Then, we have the class called SumCalculator, which inherits from HistoryCalculator and implements the two interfaces.
As you can see, SumCalculator is required to implement the declared members of the interfaces and is able to use the derived state and behavior from HistoryCalculator.

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

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