A-S*_*A-S 10 switch-statement typescript
noFallthroughCasesInSwitch我已在 tsconfig.json 文件中启用该选项。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;
}
Run Code Online (Sandbox Code Playgroud)
该错误也可以在此链接中看到:link。但是 TS Playground 有一个bug,所以你必须手动点击“TS Config”菜单,然后勾选该noFallthroughCasesInSwitch选项才能打开它,否则,你不会看到错误。
T.J*_*der 22
三个选项:
@ts-ignore抑制错误正如您所做的那样,我总是会添加一条明确的评论,包括它的含义case:
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;
}
Run Code Online (Sandbox Code Playgroud)
@ts-expect-error(TypeScript 3.9+)或者使用 TypeScript 3.9,@ts-expect-error如果有人编辑代码(或配置)以使错误消失,TypeScript 会发出警告:
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;
}
Run Code Online (Sandbox Code Playgroud)
或者,堆叠标签,使case 1标签为空(它仍然会掉落,但 TypeScriptnoFallthroughCasesInSwitch只会由掉落的非空大小写标签触发,而不是堆叠的标签[空标签后跟非空标签]):
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;
}
Run Code Online (Sandbox Code Playgroud)
A-S*_*A-S 12
我最终解决这个问题的方法是:我禁用了noFallthroughCasesInSwitchtsconfig.json 文件中的选项并安装了 ESLint。
TypeScript 几乎不做 linting,并且曾经使用 TSLint 作为补充 linter,现在已弃用并由 ESLint 取代。
我个人的观点是,TypeScript 本身不应该建议对不会导致构建过程失败的代码进行任何更改,并且应该使用 ESList 等第 3 方 linting 工具。只做一些 linting - 会导致不完善的规则和问题,就像我上面的问题一样。
| 归档时间: |
|
| 查看次数: |
16277 次 |
| 最近记录: |