TypeScript Wiki
Cover every variant with switch
Give both versions of buttonColor the same input. Remove the secondary case to see which call can reach the end without returning a color.
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 · All four inputs return colors, but TypeScript cannot prove these separate if statements cover every path.
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";
}
} Type check passed. Every member of the union has a case that returns a string.
switch
function buttonColor(props: ButtonProps): string {
switch (props.variant) {
case "danger":
return "red";
case "primary":
return "blue";
case "ghost":
return "gray";
}
} TS2366 · secondary has no matching case. That call reaches the end and returns undefined, which the declared string return type excludes.
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";
}
} Type check passed. Every member of the union has a case that returns a string.
switch
function buttonColor(props: ButtonProps): string {
switch (props.variant) {
case "danger":
return "red";
case "primary":
return "blue";
case "ghost":
return "gray";
default:
return "gray";
}
} Type check passed. With no secondary case, default returns gray for secondary.
How to read a case
switch reads props.variant. Each case is an entry point: a value of "ghost" enters at case "ghost". Its return ends the function, so it needs no break. TypeScript checks every possible input, even while you are trying just one.