class Shape {
calculateArea(): number {
throw new Error('Method calculateArea not implemented.');
}
}
class Circle extends Shape {
constructor(private radius: number) {
super();
}
calculateArea(): number {
return Math.PI * this.radius * this.radius;
}
}
class Rectangle extends Shape {
constructor(private width: number, private height: number) {
super();
}
calculateArea(): number {
return this.width * this.height;
}
}
function sumAreas(shapes: Shape[]): number {
return shapes.reduce((total, shape) => total + shape.calculateArea(), 0);
}
// 示例使用
const circle = new Circle(5);
const rectangle = new Rectangle(4, 6);
const shapesArray: Shape[] = [circle, rectangle];
const totalArea = sumAreas(shapesArray);
console.log(`总面积: ${totalArea}`);