首页 > 解决方案 > noFallthroughCasesInSwitch - 明确允许通过

问题描述

  1. noFallthroughCasesInSwitch在 tsconfig.json 文件中启用了该选项。
  2. 该选项警告我一个“错误”,我想让 Typescript 编译器知道这是故意的。
  3. 它没有记录,在线示例对我不起作用 - 我如何将其标记为故意的?
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;
}

该错误也可以在此链接中看到:link。但是 TS Playground 有一个bug,所以你必须手动点击“TS Config”菜单,然后勾选这个noFallthroughCasesInSwitch选项,它就会被打开,否则你不会看到错误。

标签: typescriptswitch-statement

解决方案


三个选项:

1 -@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;
}

2 - 使用@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;
}

3 - 不要跌倒

或者,堆叠标签,使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;
}

推荐阅读