MST

星途 面试题库

面试题:TypeScript 接口在类继承中的复杂应用

定义一个接口 `Shape`,包含属性 `area: number` 和方法 `calculateArea(): void`。接着定义一个基类 `TwoDShape` 实现 `Shape` 接口,该基类有属性 `width` 和 `height`,并实现 `calculateArea` 方法计算矩形面积。再定义一个子类 `Triangle` 继承自 `TwoDShape`,重写 `calculateArea` 方法计算三角形面积。请用TypeScript 实现上述功能。
18.4万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
// 定义接口
interface Shape {
    area: number;
    calculateArea(): void;
}

// 定义基类
class TwoDShape implements Shape {
    area: number;
    width: number;
    height: number;

    constructor(width: number, height: number) {
        this.width = width;
        this.height = height;
        this.area = 0;
    }

    calculateArea(): void {
        this.area = this.width * this.height;
    }
}

// 定义子类
class Triangle extends TwoDShape {
    calculateArea(): void {
        this.area = (this.width * this.height) / 2;
    }
}