Ohm-Management - Projektarbeit B-ME
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

valid-typeof.js 2.8KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /**
  2. * @fileoverview Ensures that the results of typeof are compared against a valid string
  3. * @author Ian Christian Myers
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Rule Definition
  8. //------------------------------------------------------------------------------
  9. module.exports = {
  10. meta: {
  11. type: "problem",
  12. docs: {
  13. description: "enforce comparing `typeof` expressions against valid strings",
  14. category: "Possible Errors",
  15. recommended: true,
  16. url: "https://eslint.org/docs/rules/valid-typeof"
  17. },
  18. schema: [
  19. {
  20. type: "object",
  21. properties: {
  22. requireStringLiterals: {
  23. type: "boolean"
  24. }
  25. },
  26. additionalProperties: false
  27. }
  28. ]
  29. },
  30. create(context) {
  31. const VALID_TYPES = ["symbol", "undefined", "object", "boolean", "number", "string", "function"],
  32. OPERATORS = ["==", "===", "!=", "!=="];
  33. const requireStringLiterals = context.options[0] && context.options[0].requireStringLiterals;
  34. /**
  35. * Determines whether a node is a typeof expression.
  36. * @param {ASTNode} node The node
  37. * @returns {boolean} `true` if the node is a typeof expression
  38. */
  39. function isTypeofExpression(node) {
  40. return node.type === "UnaryExpression" && node.operator === "typeof";
  41. }
  42. //--------------------------------------------------------------------------
  43. // Public
  44. //--------------------------------------------------------------------------
  45. return {
  46. UnaryExpression(node) {
  47. if (isTypeofExpression(node)) {
  48. const parent = context.getAncestors().pop();
  49. if (parent.type === "BinaryExpression" && OPERATORS.indexOf(parent.operator) !== -1) {
  50. const sibling = parent.left === node ? parent.right : parent.left;
  51. if (sibling.type === "Literal" || sibling.type === "TemplateLiteral" && !sibling.expressions.length) {
  52. const value = sibling.type === "Literal" ? sibling.value : sibling.quasis[0].value.cooked;
  53. if (VALID_TYPES.indexOf(value) === -1) {
  54. context.report({ node: sibling, message: "Invalid typeof comparison value." });
  55. }
  56. } else if (requireStringLiterals && !isTypeofExpression(sibling)) {
  57. context.report({ node: sibling, message: "Typeof comparisons should be to string literals." });
  58. }
  59. }
  60. }
  61. }
  62. };
  63. }
  64. };