【问题标题】:How to make unreachable code warnings to be shown as errors in VSCode?如何使无法访问的代码警告在 VSCode 中显示为错误?
【发布时间】:2021-09-10 18:45:28
【问题描述】:

我在项目的tsconfig.json中配置了"allowUnreachableCode": false,下面的代码会在VSCode中显示警告:

const fn = () => {
  return
  // ???? no-unreachable warning
  console.log()
}

如何让它显示为错误?

【问题讨论】:

    标签: typescript visual-studio-code eslint tsconfig typescript-eslint


    【解决方案1】:

    短版

    将 VS Code 设置中的reportStyleChecksAsWarnings 设置为false

    加长版

    如果您检查 VS Code IDE 的源代码,特别是 typeScriptServiceClientHost 模块,您会发现 TypeScript 诊断错误 #7027 包含在以下 Set 中(上面的注释不言自明):

    // Style check diagnostics that can be reported as warnings
    const styleCheckDiagnostics = new Set([
        ...errorCodes.variableDeclaredButNeverUsed,
        ...errorCodes.propertyDeclaretedButNeverUsed,
        ...errorCodes.allImportsAreUnused,
        ...errorCodes.unreachableCode,
        ...errorCodes.unusedLabel,
        ...errorCodes.fallThroughCaseInSwitch,
        ...errorCodes.notAllCodePathsReturnAValue,
    ]);
    

    这个Set 然后用在isStyleCheckDiagnostic 方法中,定义如下:

    private isStyleCheckDiagnostic(code: number | undefined): boolean {
        return typeof code === 'number' && styleCheckDiagnostics.has(code);
    }
    

    这反过来又用于确定错误严重性的getDiagnosticSeverity 方法。从下面可以看到,严重性设置为vscode.DiagnosticSeverity.Warning;

    if (this.reportStyleCheckAsWarnings
        && this.isStyleCheckDiagnostic(diagnostic.code)
        && diagnostic.category === PConst.DiagnosticCategory.error
    ) {
        return vscode.DiagnosticSeverity.Warning;
    }
    

    请注意,仅当reportStyleChecksAsWarningstrue(默认为which is)时才会发生这种情况。因为它暴露在设置中,所以打开settings.json(你可能可以用编辑器来做,但我更喜欢这种方式)并添加:

    "typescript.reportStyleChecksAsWarnings": false
    

    重启主机,瞧,漂亮的波浪线出现了,代码报问题:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-17
      • 2015-05-22
      • 2023-03-13
      • 2016-09-03
      • 1970-01-01
      • 2023-03-28
      • 1970-01-01
      • 2021-04-25
      相关资源
      最近更新 更多