Skip to content
← Back to rules

eslint/no-implicit-coercion 风格

An auto-fix is available for this rule.

它的作用

禁止使用 !!+""+ 等运算符进行简写类型转换。

为什么这是不好的?

使用运算符进行隐式类型转换可能不如使用显式的类型转换函数(如 Boolean()Number()String())清晰。使用显式转换可以使意图更明确,代码更具可读性。

示例

此规则的 错误 代码示例:

javascript
var b = !!foo;
var n = +foo;
var s = "" + foo;

此规则的 正确 代码示例:

javascript
var b = Boolean(foo);
var n = Number(foo);
var s = String(foo);

配置

此规则接受一个配置对象,包含以下属性:

allow

type: string[]

允许的运算符列表。有效值:"!!""~""+""-""- -""*"

boolean

type: boolean

默认值:true

当为 true 时,会对隐式布尔值转换(例如 !!foo)发出警告。

disallowTemplateShorthand

type: boolean

默认值:false

当为 true 时,禁止使用模板字面量进行字符串转换(例如 `${foo}`)。

number

type: boolean

默认值:true

当为 true 时,会对隐式数字转换(例如 +foo)发出警告。

string

type: boolean

默认值:true

当为 true 时,会对隐式字符串转换(例如 "" + foo)发出警告。

如何使用

通过配置文件或 CLI 启用此规则,可以使用:

json
{
  "rules": {
    "no-implicit-coercion": "error"
  }
}
bash
oxlint --deny no-implicit-coercion

参考资料