MST

星途 面试题库

面试题:TypeScript接口的继承与联合类型应用

声明一个基础接口`Shape`,包含属性`color`(字符串类型)。再声明两个接口`Circle`和`Rectangle`,它们继承自`Shape`。`Circle`需额外有属性`radius`(数字类型),`Rectangle`需额外有属性`width`和`height`(数字类型)。最后声明一个函数`draw`,它接受`Circle`或`Rectangle`类型的联合类型参数,并根据传入的不同形状进行不同的绘制逻辑输出(例如`console.log`出相应形状及颜色等信息),请实现上述代码。
19.8万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
// 声明基础接口Shape
interface Shape {
    color: string;
}

// 声明Circle接口,继承自Shape
interface Circle extends Shape {
    radius: number;
}

// 声明Rectangle接口,继承自Shape
interface Rectangle extends Shape {
    width: number;
    height: number;
}

// 声明draw函数
function draw(shape: Circle | Rectangle) {
    if ('radius' in shape) {
        console.log(`绘制圆形,颜色:${shape.color},半径:${shape.radius}`);
    } else {
        console.log(`绘制矩形,颜色:${shape.color},宽:${shape.width},高:${shape.height}`);
    }
}