From 5f92d28e5299a59e120a993bfd4c74dc4ec3a6c6 Mon Sep 17 00:00:00 2001 From: Andrew Clark Date: Tue, 28 Feb 2017 13:04:33 -0800 Subject: [PATCH] New ESLint rule that warns against Boolean and String constructors --- .eslintrc.js | 1 + .../boolean-and-string-constructors.js | 35 +++++++++++++++++++ eslint-rules/index.js | 1 + 3 files changed, 37 insertions(+) create mode 100644 eslint-rules/boolean-and-string-constructors.js diff --git a/.eslintrc.js b/.eslintrc.js index fda855f401..7f42585cf2 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -55,6 +55,7 @@ module.exports = { // CUSTOM RULES // the second argument of warning/invariant should be a literal string 'react-internal/warning-and-invariant-args': ERROR, + 'react-internal/boolean-and-string-constructors': ERROR, }, globals: { diff --git a/eslint-rules/boolean-and-string-constructors.js b/eslint-rules/boolean-and-string-constructors.js new file mode 100644 index 0000000000..fcf13c2ccf --- /dev/null +++ b/eslint-rules/boolean-and-string-constructors.js @@ -0,0 +1,35 @@ +/** + * Copyright 2015-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @emails react-core +*/ + +'use strict'; + +module.exports = function(context) { + function check(node) { + const name = node.callee.name; + let msg = null; + switch (name) { + case 'Boolean': + msg = 'To cast a value to a boolean, use double negation: !!value'; + break; + case 'String': + msg = 'To cast a value to a string, concat it with the empty string: \'\' + value'; + break; + } + if (msg) { + context.report(node, `Do not use the ${name} constructor. ${msg}`); + } + } + + return { + CallExpression: check, + NewExpression: check, + }; +}; diff --git a/eslint-rules/index.js b/eslint-rules/index.js index 5efee2d47c..accd0e675c 100644 --- a/eslint-rules/index.js +++ b/eslint-rules/index.js @@ -3,5 +3,6 @@ module.exports = { rules: { 'warning-and-invariant-args': require('./warning-and-invariant-args'), + 'boolean-and-string-constructors': require('./boolean-and-string-constructors'), }, };