no-implicit-coercion
禁用简写类型转换
在 JavaScript 中,有很多不同的方法来转换值类型。 其中一些可能难以阅读和理解。
例如
const b = !!foo;
const b1 = ~foo.indexOf(".");
const n = +foo;
const n1 = -(-foo);
const n2 = foo - 0;
const n3 = 1 * foo;
const s = "" + foo;
foo += ``;
这些可以用以下代码替换
const b = Boolean(foo);
const b1 = foo.indexOf(".") !== -1;
const n = Number(foo);
const n1 = Number(foo);
const n2 = Number(foo);
const n3 = Number(foo);
const s = String(foo);
foo = String(foo);
规则详情
此规则旨在标记类型转换的简写符号,然后建议更易于理解的符号。
选项
此规则有三个主要选项和一个覆盖选项,以根据需要允许某些强制转换。
"boolean"
(默认为true
)- 当此项为true
时,此规则会警告boolean
类型的简写类型转换。"number"
(默认为true
)- 当此项为true
时,此规则会警告number
类型的简写类型转换。"string"
(默认为true
)- 当此项为true
时,此规则会警告string
类型的简写类型转换。"disallowTemplateShorthand"
(默认为false
)- 当此项为true
时,此规则会警告使用${expression}
形式的string
类型转换。"allow"
(默认为empty
)- 此数组中的每个条目可以是~
、!!
、+
、- -
、-
或*
中的一个,这些运算符将被允许。
请注意,allow
列表中的运算符 +
将允许 +foo
(数字强制转换)以及 "" + foo
(字符串强制转换)。
boolean
对于默认的 { "boolean": true }
选项,不正确代码的示例
在 Playground 中打开
/*eslint no-implicit-coercion: "error"*/
const b = ;
const b1 = ;
// bitwise not is incorrect only with `indexOf`/`lastIndexOf` method calling.
对于默认的 { "boolean": true }
选项,正确代码的示例
在 Playground 中打开
/*eslint no-implicit-coercion: "error"*/
const b = Boolean(foo);
const b1 = foo.indexOf(".") !== -1;
const n = ~foo; // This is a just bitwise not.
number
对于默认的 { "number": true }
选项,不正确代码的示例
在 Playground 中打开
/*eslint no-implicit-coercion: "error"*/
const n = ;
const n1 = ;
const n2 = ;
const n3 = ;
对于默认的 { "number": true }
选项,正确代码的示例
在 Playground 中打开
/*eslint no-implicit-coercion: "error"*/
const n = Number(foo);
const n1 = parseFloat(foo);
const n2 = parseInt(foo, 10);
const n3 = foo * 1/4; // `* 1` is allowed when followed by the `/` operator
string
对于默认的 { "string": true }
选项,不正确代码的示例
在 Playground 中打开
/*eslint no-implicit-coercion: "error"*/
const s = ;
const s1 = ;
;
;
对于默认的 { "string": true }
选项,正确代码的示例
在 Playground 中打开
/*eslint no-implicit-coercion: "error"*/
const s = String(foo);
foo = String(foo);
disallowTemplateShorthand
此选项不受 string
选项的影响。
对于 { "disallowTemplateShorthand": true }
选项,不正确代码的示例
在 Playground 中打开
/*eslint no-implicit-coercion: ["error", { "disallowTemplateShorthand": true }]*/
const s = ;
对于 { "disallowTemplateShorthand": true }
选项,正确代码的示例
在 Playground 中打开
/*eslint no-implicit-coercion: ["error", { "disallowTemplateShorthand": true }]*/
const s = String(foo);
const s1 = `a${foo}`;
const s2 = `${foo}b`;
const s3 = `${foo}${bar}`;
const s4 = tag`${foo}`;
对于默认的 { "disallowTemplateShorthand": false }
选项,正确代码的示例
在 Playground 中打开
/*eslint no-implicit-coercion: ["error", { "disallowTemplateShorthand": false }]*/
const s = `${foo}`;
allow
使用 allow
列表,我们可以覆盖并允许特定的运算符。
对于示例 { "allow": ["!!", "~"] }
选项,正确代码的示例
在 Playground 中打开
/*eslint no-implicit-coercion: [2, { "allow": ["!!", "~"] } ]*/
const b = !!foo;
const b1 = ~foo.indexOf(".");
何时不使用
如果您不想收到关于类型转换简写符号的通知,您可以安全地禁用此规则。
版本
此规则在 ESLint v1.0.0-rc-2 中引入。