Skip to content
← Back to rules

unicorn/no-useless-spread 正确性

This rule is turned on by default.
An auto-fix is available for this rule.

它做了什么

禁止在以下不必要的场景中使用展开语法:

  • 将数组字面量作为数组字面量的元素进行展开
  • 将数组字面量作为函数调用或 new 调用的参数进行展开
  • 将对象字面量作为对象字面量的属性进行展开
  • 使用展开语法克隆内联创建的数组

为什么这是不好的?

以下内置构造函数接受可迭代对象,因此无需将可迭代对象转换为数组:

  • Map 构造函数
  • WeakMap 构造函数
  • Set 构造函数
  • WeakSet 构造函数
  • TypedArray 构造函数
  • Array.from(…)
  • TypedArray.from(…)
  • Promise.{all,allSettled,any,race}(…)
  • Object.fromEntries(…)

for…of 循环可以遍历任意可迭代对象,而不仅仅是数组,因此无需将可迭代对象转换为数组。

yield* 可以委托给另一个可迭代对象,因此无需将可迭代对象转换为数组。

示例

此规则的错误代码示例:

javascript
const array = [firstElement, ...[secondElement], thirdElement];

await Promise.all([...iterable]);

for (const foo of [...set]);

function* foo() {
  yield* [...anotherGenerator()];
}

function foo(bar) {
  return [...bar.map((x) => x * 2)];
}

此规则的正确代码示例:

javascript
const array = [firstElement, secondElement, thirdElement];

await Promise.all(iterable);

for (const foo of set);

function* foo() {
  yield* anotherGenerator();
}

function foo(bar) {
  return bar.map((x) => x * 2);
}

如何使用

要通过配置文件或命令行启用此规则,可以使用:

json
{
  "rules": {
    "unicorn/no-useless-spread": "error"
  }
}
bash
oxlint --deny unicorn/no-useless-spread

参考资料