Skip to content

Commit 35d4489

Browse files
authored
Rule fix: no-extend: Only fix if first arg is object literal (#330)
If the first argument is a variable which could be null or undefined, then Object.assign will throw. We could convert to `Object.assign( foo || {}, ... )` but in most cases this is unnecessary, so probably better to leave it to users to fix manually.
1 parent f3e29be commit 35d4489

File tree

3 files changed

+9
-1
lines changed

3 files changed

+9
-1
lines changed

docs/rules/no-extend.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ $.extend( { myUtil: fn } );
2727
❌ Examples of **incorrect** code with `[{"allowDeep":true}]` options:
2828
```js
2929
$.extend( {}, foo );
30+
$.extend( fooCouldBeNull, doesNotAutofix );
3031
```
3132

3233
✔️ Examples of **correct** code with `[{"allowDeep":true}]` options:

src/rules/no-extend.js

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,9 @@ module.exports = {
4848
node,
4949
message: 'Prefer Object.assign or the spread operator to $.extend',
5050
fix: function ( fixer ) {
51-
if ( !isDeep ) {
51+
// Only auto-fix if we are sure the first argument is an object.
52+
// If it is undefined or null variable, then Object.assign will throw.
53+
if ( !isDeep && node.arguments[ 0 ] && node.arguments[ 0 ].type === 'ObjectExpression' ) {
5254
return fixer.replaceText( node.callee, 'Object.assign' );
5355
}
5456
}

tests/rules/no-extend.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,11 @@ ruleTester.run( 'no-extend', rule, {
3232
options: [ { allowDeep: true } ],
3333
errors: [ error ],
3434
output: 'Object.assign({}, foo)'
35+
},
36+
{
37+
code: '$.extend(fooCouldBeNull, doesNotAutofix)',
38+
options: [ { allowDeep: true } ],
39+
errors: [ error ]
3540
}
3641
]
3742
} );

0 commit comments

Comments
 (0)