From d1cf17fa6b0c2ccf9187c9e883cbcd16229047ff Mon Sep 17 00:00:00 2001 From: Ed Sanders Date: Fri, 21 Jun 2024 13:26:52 +0100 Subject: [PATCH] Rule fix: `no-extend`: Only fix if first arg is object literal 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. --- src/rules/no-extend.js | 4 +++- tests/rules/no-extend.js | 5 +++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/src/rules/no-extend.js b/src/rules/no-extend.js index 99f61b5..6addf21 100644 --- a/src/rules/no-extend.js +++ b/src/rules/no-extend.js @@ -48,7 +48,9 @@ module.exports = { node, message: 'Prefer Object.assign or the spread operator to $.extend', fix: function ( fixer ) { - if ( !isDeep ) { + // Only auto-fix if we are sure the first argument is an object. + // If it is undefined or null variable, then Object.assign will throw. + if ( !isDeep && node.arguments[ 0 ] && node.arguments[ 0 ].type === 'ObjectExpression' ) { return fixer.replaceText( node.callee, 'Object.assign' ); } } diff --git a/tests/rules/no-extend.js b/tests/rules/no-extend.js index dd04dd3..4d39caa 100644 --- a/tests/rules/no-extend.js +++ b/tests/rules/no-extend.js @@ -32,6 +32,11 @@ ruleTester.run( 'no-extend', rule, { options: [ { allowDeep: true } ], errors: [ error ], output: 'Object.assign({}, foo)' + }, + { + code: '$.extend(fooCouldBeNull, bar)', + options: [ { allowDeep: true } ], + errors: [ error ] } ] } );