【问题标题】:noFallthroughCasesInSwitch - explicitly allow fall throughnoFallthroughCasesInSwitch - 明确允许通过
【发布时间】:2021-09-15 11:06:49
【问题描述】:
  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。 但是TS Playground中有bug,所以你必须手动点击“TS Config”菜单,然后勾选noFallthroughCasesInSwitch选项,它会被打开,否则你不会看到错误。

【问题讨论】:

    标签: typescript switch-statement


    【解决方案1】:

    三个选项:

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

    【讨论】:

      【解决方案2】:

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

      TypeScript 很少进行 linting,过去将 TSLint 作为补充 linter,现在已弃用并由 ESLint 取代。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-01-04
        • 1970-01-01
        • 2019-11-29
        • 1970-01-01
        • 1970-01-01
        • 2017-02-24
        • 1970-01-01
        相关资源
        最近更新 更多