【问题标题】:Typescript Tagged Unions - Can the compiler warn you about missed branch cases?Typescript Tagged Unions - 编译器可以警告您错过的分支案例吗?
【发布时间】:2017-08-11 04:29:36
【问题描述】:

我是 TypeScript 的新手。我有以下代码:

type Circle = { kind: "circle" }
type Rectangle = { kind: "rectangle" }
type Triangle = { kind: "triangle" }
type Shape = Circle | Rectangle | Triangle

function numberOfSides(shape: Shape) {
    switch (shape.kind) {
        case "circle": return 0;
    }
}

目前编译良好。是否有任何配置或选项,以便编译器可以警告我我的 switch 语句中缺少案例?

【问题讨论】:

    标签: typescript discriminated-union


    【解决方案1】:

    是的,您只需要两件事 - 1. 打开 strictNullChecksnoImplicitReturns。 2. 将numberOfSides'返回类型标记为Number。那时编译器会发现你没有处理所有情况并给你这个错误:

    函数缺少结束返回语句,返回类型不包括“未定义”。

    【讨论】:

    • 非常感谢。你为我指明了正确的方向。我发现了 tsconfig compilerOptions。你的方式有效,但我也设置了 noImplicitReturns 选项,这似乎也有效。也许您可以将其作为另一种选择来更新您的答案?
    猜你喜欢
    • 2021-06-19
    • 1970-01-01
    • 2012-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多