Typescript标记的联合-编译器是否可以警告您缺少分支案例?
我是打字新手。我有以下代码:Typescript标记的联合-编译器是否可以警告您缺少分支案例?,typescript,discriminated-union,Typescript,Discriminated Union,我是打字新手。我有以下代码: 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 "cir
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语句中缺少case?是的,您只需要两件事-1。启用
strictNullChecks
或nomplicitreturns
。2.将numberOfSides
”返回类型标记为Number
。此时,编译器将发现您没有处理所有情况,并给出以下错误:
函数缺少结束返回语句,返回类型不包括“undefined”
非常感谢。你给我指明了正确的方向。我发现了tsconfig编译器选项。你的方法行得通,但我也设置了noImplicitReturns选项,这似乎也行得通。也许你可以更新你的答案作为另一个选择?