diff --git a/packages/eslint-plugin/src/rules/no-unnecessary-condition.ts b/packages/eslint-plugin/src/rules/no-unnecessary-condition.ts index 942048bce0b..51d42f82926 100644 --- a/packages/eslint-plugin/src/rules/no-unnecessary-condition.ts +++ b/packages/eslint-plugin/src/rules/no-unnecessary-condition.ts @@ -330,6 +330,7 @@ export default createRule({ if (isStrictNullChecks) { const UNDEFINED = ts.TypeFlags.Undefined; const NULL = ts.TypeFlags.Null; + const VOID = ts.TypeFlags.Void; const isComparable = (type: ts.Type, flag: ts.TypeFlags): boolean => { // Allow comparison to `any`, `unknown` or a naked type parameter. flag |= @@ -339,7 +340,7 @@ export default createRule({ // Allow loose comparison to nullish values. if (node.operator === '==' || node.operator === '!=') { - flag |= NULL | UNDEFINED; + flag |= NULL | UNDEFINED | VOID; } return isTypeFlagSet(type, flag); @@ -347,9 +348,9 @@ export default createRule({ if ( (leftType.flags === UNDEFINED && - !isComparable(rightType, UNDEFINED)) || + !isComparable(rightType, UNDEFINED | VOID)) || (rightType.flags === UNDEFINED && - !isComparable(leftType, UNDEFINED)) || + !isComparable(leftType, UNDEFINED | VOID)) || (leftType.flags === NULL && !isComparable(rightType, NULL)) || (rightType.flags === NULL && !isComparable(leftType, NULL)) ) { diff --git a/packages/eslint-plugin/tests/rules/no-unnecessary-condition.test.ts b/packages/eslint-plugin/tests/rules/no-unnecessary-condition.test.ts index d5fd8a8e5b3..f8401399a20 100644 --- a/packages/eslint-plugin/tests/rules/no-unnecessary-condition.test.ts +++ b/packages/eslint-plugin/tests/rules/no-unnecessary-condition.test.ts @@ -45,7 +45,7 @@ const unnecessaryConditionTest = ( errors: [ruleError(4, 12, messageId)], }); -ruleTester.run('no-unnecessary-conditionals', rule, { +ruleTester.run('no-unnecessary-condition', rule, { valid: [ ` declare const b1: boolean; @@ -67,6 +67,11 @@ for (let i = 0; b1 && b2; i++) { } const t1 = b1 && b2 ? 'yes' : 'no'; for (;;) {} + `, + ` +declare function foo(): number | void; +const result1 = foo() === undefined; +const result2 = foo() == null; `, necessaryConditionTest('false | 5'), // Truthy literal and falsy literal necessaryConditionTest('boolean | "foo"'), // boolean and truthy literal