Skip to content
← Back to rules

unicorn/new-for-builtins 严格

An auto-fix is available for this rule.

作用

强制对以下内置构造函数使用 newObjectArrayArrayBufferBigInt64ArrayBigUint64ArrayDataViewDateErrorFloat32ArrayFloat64ArrayFunctionInt8ArrayInt16ArrayInt32ArrayMapWeakMapSetWeakSetPromiseRegExpUint8ArrayUint16ArrayUint32ArrayUint8ClampedArraySharedArrayBufferProxyWeakRefFinalizationRegistry

禁止对以下内置构造函数使用 newStringNumberBooleanSymbolBigInt

为什么这是不好的?

不一致地使用 new 可能导致混淆。像 ArrayRegExp 这样的构造函数应始终使用 new,以确保获得预期的实例类型。而 StringNumberBooleanSymbolBigInt 不应使用 new,因为它们会创建对象包装器,而不是原始值。

示例

此规则的 错误 代码示例:

javascript
const foo = new String("hello world");
const bar = Array(1, 2, 3);

此规则的 正确 代码示例:

javascript
const foo = String("hello world");
const bar = new Array(1, 2, 3);

如何使用

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

json
{
  "rules": {
    "unicorn/new-for-builtins": "error"
  }
}
bash
oxlint --deny unicorn/new-for-builtins

参考资料