Search⌘ K

Solution: TypeScript Inheritance

Explore how TypeScript inheritance works by examining an abstract Shape class and its subclasses Circle, Square, and Triangle. Understand implementation of abstract methods and calculate areas, helping you structure Angular applications more effectively using object-oriented principles.

We'll cover the following...

The solution to the previous challenge is given below:

TypeScript 4.9.5
abstract class Shape {
constructor(public name: string) {}
abstract calculateArea(): number;
}
class Circle extends Shape {
constructor(public radius: number, name: string) {
super(name);
}
calculateArea(): number {
return Number((Math.PI * this.radius ** 2).toFixed(2));
}
}
class Square extends Shape {
constructor(public sideLength: number, name: string) {
super(name);
}
calculateArea(): number {
return this.sideLength ** 2;
}
}
class Triangle extends Shape {
constructor(public base: number, public height: number, name: string) {
super(name);
}
calculateArea(): number {
return 0.5 * this.base * this.height;
}
}

Explanation

  • Lines 1–4: We define an abstract class named Shape. It has a constructor that accepts a ...