1.

Explain the concept of inheritance in TypeScript.

Answer»

Inheritance ALLOWS a class to extend ANOTHER class and reuse and modify the BEHAVIOR defined in the other class. The class which inherits another class is CALLED the derived class, and the class getting inherited is called the base class.

In TypeScript, a class can only extend one class. TypeScript USES the keyword ‘extends’ to specify the relationship between the base class and the derived classes.

class Rectangle {length: number;breadth: numberconstructor(length: number, breadth: number) { this.length = length; this.breadth = breadth}area(): number { return this.length * this.breadth;}}class Square extends Rectangle {constructor(side: number) { super(side, side);}volume() { return "Square doesn't have a volume!"}}const sq = new Square(10);console.log(sq.area()); // 100console.log(sq.volume()); // "Square doesn't have a volume!"

In the above example, because the class Square extends functionality from Rectangle, we can create an instance of square and call both the area() and volume() methods.



Discussion

No Comment Found