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.

作用 ​

强制对以下内置对象使用 new:Object、Array、ArrayBuffer、BigInt64Array、BigUint64Array、DataView、Date、Error、Float16Array、Float32Array、Float64Array、Function、Int8Array、Int16Array、Int32Array、Map、WeakMap、Set、WeakSet、Promise、RegExp、Uint8Array、Uint16Array、Uint32Array、Uint8ClampedArray、SharedArrayBuffer、Proxy、WeakRef、FinalizationRegistry。

禁止对以下内置对象使用 new:String、Number、Boolean、Symbol、BigInt。

为什么这不好? ​

不一致地使用 new 可能会造成混淆。像 Array 和 RegExp 这样的构造函数应始终使用 new, 以确保得到预期的实例类型。与此同时,String、Number、Boolean、Symbol 和 BigInt 不应使用 new, 因为它们创建的是对象包装器,而不是原始值。

示例 ​

以下是此规则的错误代码示例:

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

以下是此规则的正确代码示例:

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

如何使用 ​

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 中添加。

参考资料 ​