never类型与穷尽性检查
never 表示不存在的状态
interface Circle {
kind: "circle"
radius: number
}
interface Square {
kind: "square"
sideLength: number
}
interface Triangle {
kind: "triangle"
sideLength: number
}
type Shape = Circle | Square | Triangle // 增加Triangle类型,穷尽性检查出问题。
function getArea(shape: Shape) { // 求面积
switch(shape.kind) {
case 'circle': // 圆形
return Math.PI * shape.radius ** 2
case 'square': // 方形
return shape.sideLength * 4
default: // 穷尽性检查
const _exhaustiveCheck: never = shape
return _exhaustiveCheck
}
}
网友评论