代码
提交代码
interface Rectangle { type: 'rectangle', width: number, height: number } interface Circle { type: 'circle', radius: number } interface Parallelogram { type: 'parallelogram', bottom: number, height: number } function area(shape: Rectangle | Circle | Parallelogram) { switch (shape.type) { case 'rectangle': return shape.width * shape.height case 'circle': return Math.PI * Math.pow(shape.radius, 2) case 'parallelogram': return shape.bottom * shape.height } } let shape: Circle = { type: 'circle', radius: 10 } console.log(area(shape))
运行结果