Skip to content

eqeqeq: allow null/undefined checks to simplify NonNullable checks #1453

@csvn

Description

@csvn

Using eqeq (==) in TS/JS is almost always best to avoid. But there is one use-case which is very legitimate, and that is checking for both null + undefined. I think the only thing blocking this rule from being included in recommended is this case.

function fn<T>(value: T) {
  // Replacing `undefined` with `null` works the same
  if (value != undefined) { 
    value satisfies NonNullable<T>;
  }
}

The above code is a slightly more terse but equivalent way of writing out two checks with ===:

function fn<T>(value: T) {
  if (value !== undefined && value !== null) { 
    value satisfies NonNullable<T>;
  }
}

Any other == usage is more likely to introduce bugs or unexpected behavior due to type conversion that is often hard to understand when comparing different types of values.

If this is fixed, I think it would make it very reasonable to add eqeqeq to the recommended tag.

Suggested valid code

Comparing a variable against null or undefined.

a == null;
a == undefined;
a != null;
a != undefined;

Suggested invalid code

Keep all other == + null/undefined expressions as invalid.

true == undefined;
123 != null;
// etc

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions