noFallthroughCasesInSwitch
noFallthroughCasesInSwitchはswitch文のfallthroughを禁止するコンパイラオプションです。
- デフォルト:
false - 追加されたバージョン: 1.8
解説
fallthroughとはswitchにおけるcase文でbreakまたはreturnを行わないことを意味します。case文が空でない場合に限りbreakやreturnが行われているかを厳密に評価します。
tsfunctiondaysOfMonth (month : number): number {letdays : number = 31;switch (month ) {case 1:case 3:case 5:case 7:case 8:case 10:case 12:break;case 2:days = 28;case 4:case 6:case 9:case 11:days = 30;default:throw newError ("INVALID INPUT");}returndays ;}
tsfunctiondaysOfMonth (month : number): number {letdays : number = 31;switch (month ) {case 1:case 3:case 5:case 7:case 8:case 10:case 12:break;case 2:days = 28;case 4:case 6:case 9:case 11:days = 30;default:throw newError ("INVALID INPUT");}returndays ;}
ある月の日数を求める関数daysOfMonth()を定義しましたがこの関数にはfallthroughが存在します。このオプションを有効にすると次のようなエラーが発生します。
tsfunctiondaysOfMonth (month : number): number {letdays : number = 31;switch (month ) {case 1:case 3:case 5:case 7:case 8:case 10:case 12:break;case 2:Fallthrough case in switch.7029Fallthrough case in switch.days = 28;case 4:case 6:case 9:case 11:Fallthrough case in switch.7029Fallthrough case in switch.days = 30;default:throw newError ("INVALID INPUT");}returndays ;}
tsfunctiondaysOfMonth (month : number): number {letdays : number = 31;switch (month ) {case 1:case 3:case 5:case 7:case 8:case 10:case 12:break;case 2:Fallthrough case in switch.7029Fallthrough case in switch.days = 28;case 4:case 6:case 9:case 11:Fallthrough case in switch.7029Fallthrough case in switch.days = 30;default:throw newError ("INVALID INPUT");}returndays ;}
case 1, case 3, case 5, ....がfallthroughとみなされないのはcase文の実行部分がbreakだけで何もしないからです。
これを回避するためにはcaseでは漏れなくbreakあるいはreturnをするように設計します。
tsfunctiondaysOfMonth (month : number): number {letdays : number = 31;switch (month ) {case 1:case 3:case 5:case 7:case 8:case 10:case 12:break;case 2:days = 28;break;case 4:case 6:case 9:case 11:days = 30;break;default:throw newError ("INVALID INPUT");}returndays ;}
tsfunctiondaysOfMonth (month : number): number {letdays : number = 31;switch (month ) {case 1:case 3:case 5:case 7:case 8:case 10:case 12:break;case 2:days = 28;break;case 4:case 6:case 9:case 11:days = 30;break;default:throw newError ("INVALID INPUT");}returndays ;}