Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(eslint-plugin): [no-unnecessary-condition] fix false positive with nullish coalescing #2385

Merged
merged 1 commit into from Aug 11, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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,
},
],
},
],
});