Skip to content

Commit

Permalink
fix(eslint-plugin): [no-unnecessary-condition] fix false positive wit…
Browse files Browse the repository at this point in the history
…h nullish coalescing (#2385)
  • Loading branch information
bradzacher committed Aug 11, 2020
1 parent fb6a331 commit 092c969
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
9 changes: 8 additions & 1 deletion packages/eslint-plugin/src/rules/no-unnecessary-condition.ts
Expand Up @@ -175,7 +175,14 @@ export default createRule<Options, MessageId>({

// When checking logical expressions, only check the right side
// as the left side has been checked by checkLogicalExpressionForUnnecessaryConditionals
if (node.type === AST_NODE_TYPES.LogicalExpression) {
//
// Unless the node is nullish coalescing, as it's common to use patterns like `nullBool ?? true` to to strict
// boolean checks if we inspect the right here, it'll usually be a constant condition on purpose.
// In this case it's better to inspect the type of the expression as a whole.
if (
node.type === AST_NODE_TYPES.LogicalExpression &&
node.operator !== '??'
) {
return checkNode(node.right);
}

Expand Down
Expand Up @@ -445,6 +445,14 @@ declare const key: Key;
foo?.[key]?.trim();
`,
// https://github.com/typescript-eslint/typescript-eslint/issues/2384
`
function test(testVal?: boolean) {
if (testVal ?? true) {
console.log('test');
}
}
`,
],
invalid: [
// Ensure that it's checking in all the right places
Expand Down Expand Up @@ -1367,5 +1375,25 @@ function Foo(outer: Outer, key: Bar): number | undefined {
},
],
},
// https://github.com/typescript-eslint/typescript-eslint/issues/2384
{
code: `
function test(testVal?: true) {
if (testVal ?? true) {
console.log('test');
}
}
`,
output: null,
errors: [
{
messageId: 'alwaysTruthy',
line: 3,
endLine: 3,
column: 7,
endColumn: 22,
},
],
},
],
});

0 comments on commit 092c969

Please sign in to comment.