Closed
Description
Repro
{
"rules": {
"@typescript-eslint/no-unnecessary-condition": ["error"]
}
}
function test(testVal?: boolean) {
if (testVal ?? true) {
console.log('test');
}
}
Expected Result
No ESLint errors reported (condition inside the function is falsy only when we explicitly pass testVal = false
).
Actual Result
2:20 error Unnecessary conditional, value is always truthy @typescript-eslint/no-unnecessary-condition
Additional info
I've noticed this recently when reading about additional options introduced in #1983, namely allowComparingNullableBooleansToFalse
. With that option set to false
, code like this:
function test(testVal?: boolean) {
if (testVal !== false) {
console.log('test');
}
}
... turns into this with an autofix:
function test(testVal?: boolean) {
if ((testVal ?? true)) {
console.log('test');
}
}
This is a valid transformation, since there should be only one situation when console.log()
is run - when the testVal
argument was explicitly set to false
. Therefore, no-unnecessary-condition
incorrectly reports that nullish coalescing is not needed here.
Versions
package | version |
---|---|
@typescript-eslint/eslint-plugin |
3.9.0 |
@typescript-eslint/parser |
3.9.0 |
TypeScript |
3.9.7 |
ESLint |
7.6.0 |
node |
14.7.0 |
npm |
6.14.7 |
package | version |
---|---|
@typescript-eslint/eslint-plugin |
4.0.0-rc (2edbca380bd8f317cd96bac0df5030ddcd14a6af) |
@typescript-eslint/parser |
4.0.0-rc (2edbca380bd8f317cd96bac0df5030ddcd14a6af) |
TypeScript |
4.0.0-beta |
ESLint |
7.2.0 |
node |
14.7.0 |
npm |
6.14.7 |