Code Fix

中級switchで一部returnを書き忘れた原因と直し方 › パターン3

switchで一部returnを書き忘れた原因と直し方

union型の値をswitch文で分岐する関数で、一部のケースにしかreturnを書かないと、「関数がreturn文で終わっていない」というエラーになります。

 1  type Level = { kind: "low" } | { kind: "high" };
 2  function score(l: Level): number {
 3    switch (l.kind) {
 4      case "low":
 5        return 1;
 6  _________________________________
                    ^
 7    }
 8  }
 9  console.log(score({ kind: "high" }));
main.ts(2,27): error TS2366: Function lacks ending return statement and return type does not include 'undefined'.

空欄を埋めてコンパイルを通す

広告
広告スロット(未設定)

switchで一部returnを書き忘れた原因と直し方

TypeScriptはunion型の全パターンをたどって、返し忘れがないかを検査します。

このエラーの解説と類題をまとめて見る →

広告
広告スロット(未設定)