コンテンツへスキップ
MacTokyo.
EN

TypeScript Wiki

switch で4つの variant を書き切る

同じ buttonColor に同じ値を渡して、if と switch を比べます。secondary の case を外すと、戻り値の約束を守れない道がひとつできます。

ボタンの種類

buttonColor({ label: "Save", variant: "secondary" })

ButtonProps
type ButtonProps = {
  label: string;
  variant: "primary" | "secondary" | "danger" | "ghost";
};

if

"gray"
function buttonColor(props: ButtonProps): string {
  if (props.variant === "danger") {
    return "red";
  }
  if (props.variant === "primary") {
    return "blue";
  }
  if (props.variant === "ghost") {
    return "gray";
  }
  if (props.variant === "secondary") {
    return "gray";
  }
}

TS2366 · 4つの入力には色が返ります。ただし、この if の並びでは末尾に到達しないことを型検査で証明できません。

switch

"gray"
function buttonColor(props: ButtonProps): string {
  switch (props.variant) {
    case "danger":
      return "red";
    case "primary":
      return "blue";
    case "ghost":
      return "gray";
    case "secondary":
      return "gray";
  }
}

型チェック OK。4つすべての case が文字列を返します。

case の読み方

switch は props.variant の値を調べます。case "ghost": は「その値が ghost なら、ここから実行する」という入口です。return が関数を終えるので break は不要です。赤線は現在の選択にかかわらず、すべての入力を調べた結果です。

前のページ:variant ごとの分岐