MST

星途 面试题库

面试题:TypeScript 多态性在复杂继承体系中的应用

假设有一个复杂的 TypeScript 类继承体系,基类为 Shape,有 calculateArea 方法。子类 Circle 和 Rectangle 继承自 Shape 并重写 calculateArea 方法。现在要求实现一个函数,该函数接受一个 Shape 类型的数组,遍历数组并调用每个对象的 calculateArea 方法,返回所有形状面积的总和。请编写完整代码实现。
49.4万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
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}`);