prefer-object-spread
禁止使用 Object.assign
和对象字面量作为第一个参数,而应使用对象扩展
此规则报告的一些问题可通过 --fix
命令行选项自动修复
当使用对象字面量作为第一个参数调用 Object.assign
时,此规则需要使用对象扩展语法。此规则还警告使用作为对象字面的单个参数进行 Object.assign
调用的情况,在这种情况下,不需要 Object.assign
调用。
¥When Object.assign
is called using an object literal as the first argument, this rule requires using the object spread syntax instead. This rule also warns on cases where an Object.assign
call is made using a single argument that is an object literal, in this case, the Object.assign
call is not needed.
在 ES2018 中引入的 object spread 是一种声明式替代方案,它可能比更具动态性、命令式的 Object.assign
表现更好。
¥Introduced in ES2018, object spread is a declarative alternative which may perform better than the more dynamic, imperative Object.assign
.
规则详情
¥Rule Details
此规则的错误代码示例:
¥Examples of incorrect code for this rule:
/*eslint prefer-object-spread: "error"*/
Object.assign({}, foo);
Object.assign({}, {foo: 'bar'});
Object.assign({ foo: 'bar'}, baz);
Object.assign({}, baz, { foo: 'bar' });
Object.assign({}, { ...baz });
// Object.assign with a single argument that is an object literal
Object.assign({});
Object.assign({ foo: bar });
此规则的正确代码示例:
¥Examples of correct code for this rule:
/*eslint prefer-object-spread: "error"*/
({ ...foo });
({ ...baz, foo: 'bar' });
// Any Object.assign call without an object literal as the first argument
Object.assign(foo, { bar: baz });
Object.assign(foo, bar);
Object.assign(foo, { bar, baz });
Object.assign(foo, { ...baz });
何时不使用
¥When Not To Use It
除非你的代码库支持 ES2018,否则不应使用此规则。
¥This rule should not be used unless ES2018 is supported in your codebase.
版本
此规则是在 ESLint v5.0.0-alpha.3 中引入。