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
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
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 が文字列を返します。
switch
function buttonColor(props: ButtonProps): string {
switch (props.variant) {
case "danger":
return "red";
case "primary":
return "blue";
case "ghost":
return "gray";
}
} TS2366 · secondary では一致する case がなく、末尾まで進んで undefined が返ります。宣言した string と一致しません。
switch
function buttonColor(props: ButtonProps): string {
switch (props.variant) {
case "danger":
return "red";
case "primary":
return "blue";
case "ghost":
return "gray";
case "secondary":
return "gray";
default:
return "gray";
}
} 型チェック OK。4つすべての case が文字列を返します。
switch
function buttonColor(props: ButtonProps): string {
switch (props.variant) {
case "danger":
return "red";
case "primary":
return "blue";
case "ghost":
return "gray";
default:
return "gray";
}
} 型チェック OK。secondary には専用の case がないので、default が gray を返します。
case の読み方
switch は props.variant の値を調べます。case "ghost": は「その値が ghost なら、ここから実行する」という入口です。return が関数を終えるので break は不要です。赤線は現在の選択にかかわらず、すべての入力を調べた結果です。