Skip to content

useObjectSpread

¥Summary

¥How to configure

biome.json
{
"linter": {
"rules": {
"style": {
"useObjectSpread": "error"
}
}
}
}

¥Description

构建新对象时,优先使用 Object.assign() 对象展开。

¥Prefer object spread over Object.assign() when constructing new objects.

对象扩展语法比 Object.assign() 更简洁、更易读,并且在从现有对象创建新对象时性能更好。它也拥有更好的 TypeScript 集成。

¥Object spread syntax is more concise, more readable, and performs better than Object.assign() when creating a new object from existing objects. It also has better TypeScript integration.

¥Examples

¥Invalid

Object.assign({}, foo);
code-block.js:1:1 lint/style/useObjectSpread  FIXABLE  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

ℹ Object spread syntax is more concise, readable, and performs better than Object.assign.

> 1 │ Object.assign({}, foo);
│ ^^^^^^^^^^^^^
2 │

ℹ Safe fix: Replace Object.assign({…}, <object>) with { …<object> }.

1 │ - Object.assign({},·foo);
1 │ + ({...foo,});
2 2 │

Object.assign({}, { foo: 'bar' });
code-block.js:1:1 lint/style/useObjectSpread  FIXABLE  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

ℹ Object spread syntax is more concise, readable, and performs better than Object.assign.

> 1 │ Object.assign({}, { foo: ‘bar’ });
│ ^^^^^^^^^^^^^
2 │

ℹ Safe fix: Replace Object.assign({…}, <object>) with { …<object> }.

1 │ - Object.assign({},·{·foo:·‘bar’·});
1 │ + ({foo:·‘bar’·,});
2 2 │

Object.assign({ foo: 'bar' }, baz);
code-block.js:1:1 lint/style/useObjectSpread  FIXABLE  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

ℹ Object spread syntax is more concise, readable, and performs better than Object.assign.

> 1 │ Object.assign({ foo: ‘bar’ }, baz);
│ ^^^^^^^^^^^^^
2 │

ℹ Safe fix: Replace Object.assign({…}, <object>) with { …<object> }.

1 │ - Object.assign({·foo:·‘bar’·},·baz);
1 │ + ({foo:·‘bar’·,...baz,});
2 2 │

Object.assign({}, baz, { foo: 'bar' });
code-block.js:1:1 lint/style/useObjectSpread  FIXABLE  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

ℹ Object spread syntax is more concise, readable, and performs better than Object.assign.

> 1 │ Object.assign({}, baz, { foo: ‘bar’ });
│ ^^^^^^^^^^^^^
2 │

ℹ Safe fix: Replace Object.assign({…}, <object>) with { …<object> }.

1 │ - Object.assign({},·baz,·{·foo:·‘bar’·});
1 │ + ({...baz,foo:·‘bar’·,});
2 2 │

¥Valid

({ ...foo });
({ ...baz, foo: 'bar' });

允许修改现有对象:

¥Modifying an existing object is allowed:

Object.assign(foo, { bar: baz });

¥Related links