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] handle void #5766

Merged
merged 1 commit into from Oct 7, 2022
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
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