(s: Shape)
| 56 | |
| 57 | type Shape = Square | Rectangle | Circle |
| 58 | function area(s: Shape){ // 利用两种类型的共有属性来创建不同的类型保护区块 |
| 59 | switch (s.kind){ |
| 60 | case "square": |
| 61 | return s.size * s.size; |
| 62 | case "rectangle": |
| 63 | return s.height * s.width |
| 64 | case "circle": |
| 65 | return Math.PI * s.r ** 2 |
| 66 | default: |
| 67 | return ((e: never) => {throw new Error(e)})(s) |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | console.log(area({kind: 'circle',r: 1})) |