MST

星途 面试题库

面试题:TypeScript继承与多态在复杂场景下的实践

假设你正在开发一个图形绘制库,有一个基类Shape,包含通用的属性和方法,如颜色、位置等。基于Shape类,派生出Circle、Rectangle、Triangle等子类,每个子类有自己特定的计算面积和周长的方法。要求使用TypeScript的继承与多态特性实现这个库,并且考虑如何利用extends和super来优化代码结构,同时处理好不同形状之间的共性与差异,最后请描述如何在这个库的基础上方便地扩展新的图形类型。
43.5万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
// 定义基类Shape
class Shape {
    color: string;
    position: { x: number; y: number };

    constructor(color: string, x: number, y: number) {
        this.color = color;
        this.position = { x, y };
    }
}

// 定义Circle子类
class Circle extends Shape {
    radius: number;

    constructor(color: string, x: number, y: number, radius: number) {
        super(color, x, y);
        this.radius = radius;
    }

    calculateArea(): number {
        return Math.PI * this.radius * this.radius;
    }

    calculatePerimeter(): number {
        return 2 * Math.PI * this.radius;
    }
}

// 定义Rectangle子类
class Rectangle extends Shape {
    width: number;
    height: number;

    constructor(color: string, x: number, y: number, width: number, height: number) {
        super(color, x, y);
        this.width = width;
        this.height = height;
    }

    calculateArea(): number {
        return this.width * this.height;
    }

    calculatePerimeter(): number {
        return 2 * (this.width + this.height);
    }
}

// 定义Triangle子类
class Triangle extends Shape {
    side1: number;
    side2: number;
    side3: number;

    constructor(color: string, x: number, y: number, side1: number, side2: number, side3: number) {
        super(color, x, y);
        this.side1 = side1;
        this.side2 = side2;
        this.side3 = side3;
    }

    calculateArea(): number {
        const s = (this.side1 + this.side2 + this.side3) / 2;
        return Math.sqrt(s * (s - this.side1) * (s - this.side2) * (s - this.side3));
    }

    calculatePerimeter(): number {
        return this.side1 + this.side2 + this.side3;
    }
}

如何扩展新的图形类型

  1. 创建新的子类:定义一个新的类,继承自Shape基类。例如,要添加一个Ellipse图形类型,可以这样写:
class Ellipse extends Shape {
    majorAxis: number;
    minorAxis: number;

    constructor(color: string, x: number, y: number, majorAxis: number, minorAxis: number) {
        super(color, x, y);
        this.majorAxis = majorAxis;
        this.minorAxis = minorAxis;
    }

    calculateArea(): number {
        return Math.PI * this.majorAxis * this.minorAxis;
    }

    calculatePerimeter(): number {
        // 这里使用一个近似公式
        return Math.PI * (3 * (this.majorAxis + this.minorAxis) - Math.sqrt((3 * this.majorAxis + this.minorAxis) * (this.majorAxis + 3 * this.minorAxis)));
    }
}
  1. 使用新的子类:在代码中,就可以像使用其他子类一样使用新创建的Ellipse类。例如:
const ellipse = new Ellipse('red', 0, 0, 5, 3);
console.log(`Ellipse Area: ${ellipse.calculateArea()}`);
console.log(`Ellipse Perimeter: ${ellipse.calculatePerimeter()}`);

通过这种方式,利用TypeScript的继承和多态特性,新图形类型的扩展变得非常方便,只需按照基类的模式定义新的子类,并实现特定的面积和周长计算方法即可。