Skip to content
← Back to rules

eslint/no-implicit-coercion Style

🛠️ 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

default: true

当为 true 时,警告隐式布尔强制转换(例如,!!foo)。

disallowTemplateShorthand

type: boolean

default: false

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

number

type: boolean

default: true

当为 true 时,警告隐式数字强制转换(例如,+foo)。

string

type: boolean

default: true

当为 true 时,警告隐式字符串强制转换(例如,"" + foo)。

如何使用

To enable this rule using the config file or in the CLI, you can use:

json
{
  "rules": {
    "no-implicit-coercion": "error"
  }
}
ts
import { defineConfig } from "oxlint";

export default defineConfig({
  rules: {
    "no-implicit-coercion": "error",
  },
});
bash
oxlint --deny no-implicit-coercion

版本

此规则于 v1.33.0 中新增。

参考资料