Search code examples
typescriptvisual-studio-codeeslinttsconfigtypescript-eslint

How to make unreachable code warnings to be shown as errors in VSCode?


I've configured "allowUnreachableCode": false in project's tsconfig.json, the following code will show a warning in VSCode:

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

How to make it shown as an error?


Solution

  • Short version

    Set the reportStyleChecksAsWarnings in VS Code settings to false

    Long version

    If you inspect the source code of the VS Code IDE, in particular the typeScriptServiceClientHost module, you will find out that the TypeScript diagnostics error #7027 is included in the following Set (the comment above it speaks for itself):

    // 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,
    ]);
    

    This Set is then used in the isStyleCheckDiagnostic method defined as follows:

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

    which, in turn, is used in the getDiagnosticSeverity method that determines the severity of the error. As you can see from below, the severity is set to vscode.DiagnosticSeverity.Warning;:

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

    Notice that this only happens if reportStyleChecksAsWarnings is true (which is by default). Since it is exposed to settings, open the settings.json (you probably can do it with the editor, but I prefer it this way) and add:

    "typescript.reportStyleChecksAsWarnings": false
    

    Restart the host, and voila, the nice squiggly lines are there, and the code is reported as a problem:

    test function reporting the error