no-eq-null.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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. module.exports = {
  11. meta: {
  12. type: "suggestion",
  13. docs: {
  14. description: "disallow `null` comparisons without type-checking operators",
  15. category: "Best Practices",
  16. recommended: false,
  17. url: "https://eslint.org/docs/rules/no-eq-null"
  18. },
  19. schema: [],
  20. messages: {
  21. unexpected: "Use '===' to compare with null."
  22. }
  23. },
  24. create(context) {
  25. return {
  26. BinaryExpression(node) {
  27. const badOperator = node.operator === "==" || node.operator === "!=";
  28. if (node.right.type === "Literal" && node.right.raw === "null" && badOperator ||
  29. node.left.type === "Literal" && node.left.raw === "null" && badOperator) {
  30. context.report({ node, messageId: "unexpected" });
  31. }
  32. }
  33. };
  34. }
  35. };