我是 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 语句中缺少大小写?
最佳答案
是的,您只需要两件事 - 1. 打开 strictNullChecks
或 noImplicitReturns
。 2. 将numberOfSides
的返回类型标记为Number
。那时编译器会发现你没有处理所有的情况并给你这个错误:
Function lacks ending return statement and return type does not include 'undefined'.
关于Typescript Tagged Unions - 编译器可以警告您遗漏的分支案例吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42894386/