no-implicit-coercion
Require Boolean(), Number() and String() instead of operator tricks like !!x and +x
fixable
!!value, +value and "" + value convert a value as a side effect of an operator. You have to know the trick to see that a conversion happens. Boolean(value), Number(value) and String(value) say it by name.
--fix rewrites !!value to Boolean(value). For the conversions to a number or a string, the rewrite is offered as a suggestion.
Configure#
Off by default. To turn it on:
bunfig.toml
[lint.rules]
"no-implicit-coercion" = "error" # or "warn"Every option, set to its default:
bunfig.toml
[lint.rules]
"no-implicit-coercion" = ["error", {
boolean = true,
number = true,
string = true,
disallowTemplateShorthand = false,
allow = [], # list of "~", "!!", "+", "- -", "-" or "*"
}]Examples#
example.js6 problems
const hasItems = !!items.lengthUnexpected implicit coercion encountered. Use Boolean(items.length) instead.;
const isMember = ~names.indexOf(user.name)Unexpected implicit coercion encountered. Use names.indexOf(user.name) !== -1 instead.;
const quantity = +input.valueUnexpected implicit coercion encountered. Use Number(input.value) instead.;
const price = 1 * row.priceUnexpected implicit coercion encountered. Use Number(row.price) instead.;
const id = "" + user.idUnexpected implicit coercion encountered. Use String(user.id) instead.;
label += ""Unexpected implicit coercion encountered. Use label = String(label) instead.;example.jsNo problems
const hasItems = Boolean(items.length);
const isMember = names.indexOf(user.name) !== -1;
const quantity = Number(input.value);
const price = Number(row.price);
const id = String(user.id);
label = String(label);Options#
| Option | Default | What it does |
|---|---|---|
boolean | true | Report !!value and ~list.indexOf(value). |
number | true | Report +value, - -value, 1 * value and value - 0. |
string | true | Report "" + value and value += "". |
disallowTemplateShorthand | false | Also report a template that holds one expression and nothing else. |
allow | [] | Operators to leave alone: any of "~", "!!", "+", "- -", "-", "*". |
example.jswith
{ "disallowTemplateShorthand": true }1 problemconst id = `${user.id}`Unexpected implicit coercion encountered. Use String(user.id) instead.;allow keeps one trick while the rest of its group is still reported:
example.jswith
{ "allow": ["!!"] }No problemsconst hasItems = !!items.length;example.jswith
{ "allow": ["!!"] }1 problemconst isMember = ~names.indexOf(user.name)Unexpected implicit coercion encountered. Use names.indexOf(user.name) !== -1 instead.;"+" stands for both +value and "" + value:
example.jswith
{ "allow": ["+"] }No problemsconst quantity = +input.value;
const id = "" + user.id;