noFallthroughCasesInSwitch: Preventing Switch Fallthrough
What you'll learn: How the noFallthroughCasesInSwitch compiler flag catches unintentional switch fallthrough bugs where you forget to break or return between cases.
The Switch Fallthrough Problem
In JavaScript (and TypeScript), when you use a switch statement, execution "falls through" from one case to the next unless you explicitly stop it with break, return, or throw. This behavior is intentional in the language design, but it's also a notorious source of bugs.
Imagine a restaurant order system where you check the meal type:
function getMealPrice(meal: string): number {
let price = 0;
switch (meal) {
case 'breakfast':
price = 10;
case 'lunch':
price = 15;
case 'dinner':
price = 20;
default:
price = 0;
}
return price;
}
What happens when you call getMealPrice('breakfast')? You'd expect 10, but you actually get 0! Why? Because execution falls through every case until it hits the default.
How noFallthroughCasesInSwitch Helps
When you enable noFallthroughCasesInSwitch in your tsconfig.json, TypeScript will error if a case clause has statements but doesn't end with break, return, throw, or another terminating statement.
{
"compilerOptions": {
"noFallthroughCasesInSwitch": true
}
}
With this enabled, the previous code would produce compiler errors, forcing you to fix it:
function getMealPrice(meal: string): number {
switch (meal) {
case 'breakfast':
return 10; // ✓ Terminates the case
case 'lunch':
return 15;
case 'dinner':
return 20;
default:
return 0;
}
}
When Fallthrough Is Intentional
Empty cases that deliberately fall through are still allowed:
function isWeekend(day: string): boolean {
switch (day) {
case 'Saturday':
case 'Sunday': // Empty fallthrough is fine
return true;
default:
return false;
}
}
Key Takeaway: Enable noFallthroughCasesInSwitch to catch accidental missing break or return statements in switch cases, preventing subtle bugs where code unintentionally executes multiple case blocks.