prefer-const incorrect gives an error on exported variables that are changed in a different file
See original GitHub issueTell us about your environment
Node version: v10.15.3 npm version: v6.4.1 Local ESLint version: v6.8.0 Global ESLint version: v7.2.0 (Currently used)
What parser (default, @babel/eslint-parser
, @typescript-eslint/parser
, etc.) are you using?
@typescript-eslint/parser
Please show your full configuration:
What did you do? Please include the actual source code causing the issue, as well as the command that you used to run ESLint.
file1.ts
export let test: boolean = false;
file2.ts
import mod = require('./file1');
mod.test = true;
gulp lint
What did you expect to happen?
No error 'test' is never reassigned. Use 'const' instead.
. The code won’t compile with ‘const’ because it complains in file2 that it is changing a read-only variable.
What actually happened? Please include the actual, raw output from ESLint.
error 'test' is never reassigned. Use 'const' instead.
.
Are you willing to submit a pull request to fix this bug? No.
Issue Analytics
- State:
- Created 3 years ago
- Comments:5 (3 by maintainers)
Top GitHub Comments
It is a TS compiler error to attempt to assign to an imported variable.
given:
TS will (correctly) hard error if you attempt to reassign the variable
however if you use an import assignment, then it allows it, because TS is conceding that you’re doing javascripty things with commonjs modules:
However this is a large antipattern. You should not do this. The fact that your code transpiles to commonjs under the hood is an implementation detail that shouldn’t be relied upon. If you rely upon it, when the underlying system changes to ES6 modules your code will be irrevocably broken.
Instead if you must use this pattern of mutating constants from a module, consider exporting an object:
Hi @sean-mcmanus, thanks for the issue!
I think it’s correct behavior for the core
prefer-const
rule.Per the specification for ES modules, the exported
test
cannot be reassigned from another module:Given that, the rule doesn’t account for the fact that the variable is
export
-ed, because it isn’t allowed to assign to that variable in other modules, regardless of the variable’s kind (let
orconst
).The use case you presented relies on ts compiler specifics, where
export let test
actually becomesexports.test
, so it is possible to change its value in runtime. However, supporting this build-specific behavior is out of scope for this rule.Maybe ESLint Plugin TypeScript could provide a replacement rule to support this use case (i.e., not warn on
export let
).