中級 › switchで一部returnを書き忘れた原因と直し方 › パターン4
switchで一部returnを書き忘れた原因と直し方
union型の値をswitch文で分岐する関数で、一部のケースにしかreturnを書かないと、「関数がreturn文で終わっていない」というエラーになります。
1 type Light = { kind: "red" } | { kind: "green" }; 2 function action(l: Light): string { 3 switch (l.kind) { 4 case "red": 5 return "stop"; 6 ____________________________________ ^ 7 } 8 } 9 console.log(action({ kind: "green" }));
main.ts(2,28): error TS2366: Function lacks ending return statement and return type does not include 'undefined'.
空欄を埋めてコンパイルを通す
greenのケースにreturnが無いため、switch文が値を返さずに終わる経路が生まれます。
次の問題