MST

星途 面试题库

面试题:TypeScript联合类型与类型保护的综合运用

假设有一个联合类型`type MyUnion = { type: 'circle'; radius: number } | { type:'rectangle'; width: number; height: number };`,编写一个函数`calculateArea`,该函数接受`MyUnion`类型的参数,根据不同的类型计算并返回图形的面积。要求在函数内部使用类型保护来区分不同类型,并确保类型安全。请提供完整的代码实现。
21.2万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
type MyUnion = { type: 'circle'; radius: number } | { type:'rectangle'; width: number; height: number };

function calculateArea(shape: MyUnion): number {
    if (shape.type === 'circle') {
        return Math.PI * shape.radius * shape.radius;
    } else {
        return shape.width * shape.height;
    }
}