no-eq-null.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. /**
  2. * @fileoverview Rule to flag comparisons to null without a type-checking
  3. * operator.
  4. * @author Ian Christian Myers
  5. */
  6. "use strict";
  7. //------------------------------------------------------------------------------
  8. // Rule Definition
  9. //------------------------------------------------------------------------------
  10. /** @type {import('../types').Rule.RuleModule} */
  11. module.exports = {
  12. meta: {
  13. type: "suggestion",
  14. docs: {
  15. description:
  16. "Disallow `null` comparisons without type-checking operators",
  17. recommended: false,
  18. url: "https://eslint.org/docs/latest/rules/no-eq-null",
  19. },
  20. schema: [],
  21. messages: {
  22. unexpected: "Use '===' to compare with null.",
  23. },
  24. },
  25. create(context) {
  26. return {
  27. BinaryExpression(node) {
  28. const badOperator =
  29. node.operator === "==" || node.operator === "!=";
  30. if (
  31. (node.right.type === "Literal" &&
  32. node.right.raw === "null" &&
  33. badOperator) ||
  34. (node.left.type === "Literal" &&
  35. node.left.raw === "null" &&
  36. badOperator)
  37. ) {
  38. context.report({ node, messageId: "unexpected" });
  39. }
  40. },
  41. };
  42. },
  43. };