Skip to content

Commit

Permalink
fix(eslint-plugin): [no-unnecessary-condition] handle void (#5766)
Browse files Browse the repository at this point in the history
  • Loading branch information
yeonjuan committed Oct 7, 2022
1 parent 4939ec8 commit ac8f06b
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 4 deletions.
7 changes: 4 additions & 3 deletions packages/eslint-plugin/src/rules/no-unnecessary-condition.ts
Expand Up @@ -330,6 +330,7 @@ export default createRule<Options, MessageId>({
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 |=
Expand All @@ -339,17 +340,17 @@ export default createRule<Options, MessageId>({

// Allow loose comparison to nullish values.
if (node.operator === '==' || node.operator === '!=') {
flag |= NULL | UNDEFINED;
flag |= NULL | UNDEFINED | VOID;
}

return isTypeFlagSet(type, flag);
};

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))
) {
Expand Down
Expand Up @@ -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;
Expand All @@ -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
Expand Down

0 comments on commit ac8f06b

Please sign in to comment.