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