Search code examples
typescripteslinttypescript-eslint

Why is the @typescript-eslint/no-redeclare rule indicating a false positive?


I have a typescript project where linting is supported via eslint and typescript-eslint.

Please note that this is just a minimal working example.

Here's a repl link

index.ts

function testfn(value: number) {
    if (value === 10) {
        const result = value * 2;

        return result;
    }

    const result = value * 3;

    return result;
}

console.log(testfn(11));

.eslintrc.js

module.exports = {
    root: true,
  parser: "@typescript-eslint/parser",
  parserOptions: {
    ecmaVersion: "latest",
    project: "./tsconfig.json"
  },
  plugins: ["@typescript-eslint"],
  extends: ["plugin:@typescript-eslint/recommended"],
  rules: {
    "no-redeclare": "off",
    "@typescript-eslint/no-redeclare": "error",
  },
};

tsconfig.json

{
  "compilerOptions": {
    "downlevelIteration": true,
    "strict": true,
    "esModuleInterop": true,
    "resolveJsonModule": true,
    "moduleResolution": "node",
    "sourceMap": true,
    "noImplicitReturns": true,
    "noImplicitOverride": true,
    "importHelpers": true
  }
}

package.json

{
  "name": "no-redeclare-scope-issue",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "lint": "eslint . --ext .ts"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@typescript-eslint/eslint-plugin": "^4.29.3",
    "@typescript-eslint/parser": "^4.29.3",
    "eslint": "^7.32.0",
    "tslib": "^2.3.1",
    "typescript": "^4.3.5"
  }
}

When I execute the lint script I get this lint error:

> eslint . --ext .ts


/home/runner/no-redeclare-scope-issue/index.ts
  8:8  error  'result' is already defined  @typescript-eslint/no-redeclare

✖ 1 problem (1 error, 0 warnings)

This is unexpected because the variable result declared inside the if statement should be isolated from the one declared outside of it because the if statement has its own scope.

Note that when I remove the property ecmaVersion: "latest" from .eslintrc.js I get no error.

Is this an issue or is this the expected behavior? and why?


Solution

  • The provided code no longer reports any issues with plugin:@typescript-eslint/no-redeclare. See typescript-eslint playground showing the code without lint reports.

    Creating a copy of your project with the same package-lock.json does reproduce the issue. But creating the copy without a package-lock.json (installing fresh versions of packages) no longer reproduces the error.