noFallthroughCasesInSwitch option in the tsconfig.json file.function getRandomInt(max: number) {
return Math.floor(Math.random() * max);
}
switch(getRandomInt(3)) {
/* falls through */
/* fall through */
/* FALLTHROUGH */
case 1: /* falls through */ /* fall through */ /* FALLTHROUGH */ /* <----- Still getting an error here "Fallthrough case in switch. (7029)" */
/* falls through */
/* fall through */
/* FALLTHROUGH */
console.log(1);
/* falls through */
/* fall through */
/* FALLTHROUGH */
case 2:
console.log(2);
break;
}
The error can be seen in this link as well: link.
But there's a bug in TS Playground, so you must manually click the "TS Config" menu and then Tick the noFallthroughCasesInSwitch option so it will be turned on, otherwise, you'll not see the error.
Three options:
@ts-ignore to suppress the errorAs you did, I would always include a comment being explicit about it as well, including what case it falls through to:
function getRandomInt(max: number) {
return Math.floor(Math.random() * max);
}
switch(getRandomInt(3)) {
// @ts-ignore
case 1:
console.log(1);
// FALLS THROUGH to 2
case 2:
console.log(2);
break;
}
@ts-expect-error (TypeScript 3.9+)Or with TypeScript 3.9 you might use @ts-expect-error so that if someone edits the code (or config) to make the error go away, TypeScript warns you about it:
function getRandomInt(max: number) {
return Math.floor(Math.random() * max);
}
switch(getRandomInt(3)) {
// @ts-expect-error
case 1:
console.log(1);
// FALLS THROUGH to 2
case 2:
console.log(2);
break;
}
Alternatively, stack the labels so the case 1 label is empty (it still falls through, but TypeScript's noFallthroughCasesInSwitch only gets triggered by non-empty case labels that fall through, not stacked ones [empty ones followed by non-empty ones]):
function getRandomInt(max: number) {
return Math.floor(Math.random() * max);
}
const n = getRandomInt(3);
switch(n) {
case 1:
case 2:
if (n === 1) {
console.log(1);
}
console.log(2);
break;
}
The way I finally solved it: I've disabled the noFallthroughCasesInSwitch option in the tsconfig.json file and installed ESLint instead.
TypeScript does very little linting, and used to have TSLint as a complementary linter, which is now deprecated and replaced by ESLint.
My personal opinion is that TypeScript should not suggest by themselves any changes to the code that is not expected to fail their build process, and they should use a 3rd-party linting tool like ESList. Doing only some linting - leads to non-polished rules and problems like my question above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With