Skip to content
← Back to rules

unicorn/new-for-builtins Pedantic

🚧 An auto-fix is planned for this rule, but not implemented at this time.

作用

强制对以下内置对象使用 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);

如何使用

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

json
{
  "rules": {
    "unicorn/new-for-builtins": "error"
  }
}
ts
import { defineConfig } from "oxlint";

export default defineConfig({
  rules: {
    "unicorn/new-for-builtins": "error",
  },
});
bash
oxlint --deny unicorn/new-for-builtins

版本

此规则已在 v0.0.16 中添加。

参考资料