noFallthroughCasesInSwitch - 明确允许失败

noFallthroughCasesInSwitch - explicitly allow fall through

  1. 我在 tsconfig.json 文件中启用了 noFallthroughCasesInSwitch 选项。
  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 中也可以看到错误:link。 但是TS Playground中有一个bug,所以你必须手动点击“TS Config”菜单,然后勾选noFallthroughCasesInSwitch选项,它才会被打开,否则,你将看不到错误。

三个选项:

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 标签为空(它仍然会失败,但 TypeScript 的 noFallthroughCasesInSwitch 只会被失败的非空案例标签触发,而不是堆叠的 [空的跟非空的]):

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

我最终解决的方法:我禁用了 tsconfig.json 文件中的 noFallthroughCasesInSwitch 选项并安装了 ESLint。

TypeScript 做的 linting 很少,过去曾将 TSLint 作为补充 linter,现在已弃用并由 ESLint 取而代之。

我个人的看法是,TypeScript 不应自行建议对代码进行任何预计不会使其构建过程失败的更改,并且他们应该使用 ESList 等第 3 方 linting 工具。只做一些 linting - 导致非完善的规则和问题,如我上面的问题。