美文网首页TypeScript
never类型与穷尽性检查

never类型与穷尽性检查

作者: 我的袜子都是洞 | 来源:发表于2023-01-03 21:51 被阅读0次

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
    }
    
}

相关文章

网友评论

    本文标题:never类型与穷尽性检查

    本文链接:https://www.haomeiwen.com/subject/bwmgfdtx.html