Skip to content

Commit

Permalink
feat(eslint-plugin): [no-unnecessary-cond] check logical assignments (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
Josh-Cena committed Mar 13, 2023
1 parent 36ef0e1 commit dbc203a
Show file tree
Hide file tree
Showing 2 changed files with 130 additions and 0 deletions.
13 changes: 13 additions & 0 deletions packages/eslint-plugin/src/rules/no-unnecessary-condition.ts
Expand Up @@ -636,7 +636,20 @@ export default createRule<Options, MessageId>({
checkOptionalChain(node, node.callee, '');
}

function checkAssignmentExpression(
node: TSESTree.AssignmentExpression,
): void {
// Similar to checkLogicalExpressionForUnnecessaryConditionals, since
// a ||= b is equivalent to a || (a = b)
if (['||=', '&&='].includes(node.operator)) {
checkNode(node.left);
} else if (node.operator === '??=') {
checkNodeForNullish(node.left);
}
}

return {
AssignmentExpression: checkAssignmentExpression,
BinaryExpression: checkIfBinaryExpressionIsNecessaryConditional,
CallExpression: checkCallExpression,
ConditionalExpression: (node): void => checkNode(node.test),
Expand Down
117 changes: 117 additions & 0 deletions packages/eslint-plugin/tests/rules/no-unnecessary-condition.test.ts
Expand Up @@ -548,6 +548,18 @@ interface Foo {
type OptionalFoo = Foo | undefined;
declare const foo: OptionalFoo;
foo?.[1]?.length;
`,
`
declare let foo: number | null;
foo ??= 1;
`,
`
declare let foo: number;
foo ||= 1;
`,
`
declare let foo: number;
foo &&= 1;
`,
// https://github.com/typescript-eslint/typescript-eslint/issues/6264
`
Expand Down Expand Up @@ -1676,5 +1688,110 @@ function getElem(dict: Record<string, { foo: string }>, key: string) {
},
],
},
{
code: `
declare let foo: {};
foo ??= 1;
`,
errors: [
{
messageId: 'neverNullish',
line: 3,
endLine: 3,
column: 1,
endColumn: 4,
},
],
},
{
code: `
declare let foo: number;
foo ??= 1;
`,
errors: [
{
messageId: 'neverNullish',
line: 3,
endLine: 3,
column: 1,
endColumn: 4,
},
],
},
{
code: `
declare let foo: null;
foo ??= null;
`,
errors: [
{
messageId: 'alwaysNullish',
line: 3,
endLine: 3,
column: 1,
endColumn: 4,
},
],
},
{
code: `
declare let foo: {};
foo ||= 1;
`,
errors: [
{
messageId: 'alwaysTruthy',
line: 3,
endLine: 3,
column: 1,
endColumn: 4,
},
],
},
{
code: `
declare let foo: null;
foo ||= null;
`,
errors: [
{
messageId: 'alwaysFalsy',
line: 3,
endLine: 3,
column: 1,
endColumn: 4,
},
],
},
{
code: `
declare let foo: {};
foo &&= 1;
`,
errors: [
{
messageId: 'alwaysTruthy',
line: 3,
endLine: 3,
column: 1,
endColumn: 4,
},
],
},
{
code: `
declare let foo: null;
foo &&= null;
`,
errors: [
{
messageId: 'alwaysFalsy',
line: 3,
endLine: 3,
column: 1,
endColumn: 4,
},
],
},
],
});

0 comments on commit dbc203a

Please sign in to comment.