useObjectSpread
Summary
Section titled “Summary”- Rule available since:
v2.0.0
- Diagnostic Category:
lint/nursery/useObjectSpread
- This rule has a safe fix.
- The default severity of this rule is information.
- Sources:
- Same as
prefer-object-spread
- Same as
Description
Section titled “Description”Prefer object spread over Object.assign()
when constructing new objects.
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
Section titled “Examples”Invalid
Section titled “Invalid”Object.assign({}, foo);
code-block.js:1:1 lint/nursery/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/nursery/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/nursery/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/nursery/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 │
({ ...foo });
({ ...baz, foo: 'bar' });
Modifying an existing object is allowed:
Object.assign(foo, { bar: baz });
How to configure
Section titled “How to configure”{ "linter": { "rules": { "nursery": { "useObjectSpread": "error" } } }}