`object-rest-spread` does not transpile correctly when binding is referenced in param initializer
See original GitHub issueBug Report
- I would like to work on a fix!
Input Code
({ a, ...O }, b = O, c = a) => {}
Current Behavior The code above is transformed to
(_ref, b = O, c = a) => {
let {
a
} = _ref,
O = babelHelpers.objectWithoutProperties(_ref, ["a"]);
};
where initializers b = O
and c = a
no longer refers to the destructured params.
Expected behavior/code It should transformed to
(function (_ref) {
let { a } = _ref,
O = babelHelpers.objectWithoutProperties(_ref, ["a"]);
var b = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : O;
var c = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : a;
});
Babel Configuration (babel.config.js, .babelrc, package.json#babel, cli command, .eslintrc)
- Filename:
babel.config.js
{
"plugins": { "@babel/proposal-object-rest-spread" }
}
Environment: REPL
Possible Solution I haven’t come up with a simple solution. Suggestions are welcome.
Solution 1: Fall back to transform-parameters
when such pattern is detected
i) A function param declarator contains a RestElement. ii) The declarator is also referenced by another params’ initializers.
This solution will downgrade unnecessary codes, i.e.
({ a, ...O }, b = 2, c = O) => {}
will be transformed to
(function (_ref) {
var a = _ref.a,
O = babelHelpers.objectWithoutProperties(_ref, ["a"]);
var b = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 2;
var c = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : O;
});
even when b = 2
is supported on the target platform.
Solution 2: Extract convertSingleParam
from convertParams
defined in transform-parameters
, apply convertSingleParam
if one of params satisfies the pattern mentioned above.
This solution should prevent downgrading the code as much as possible. i.e.
({ a, ...O }, b = 2, c = O) => {}
should be transformed to
(function (_ref, b = 2) {
let { a } = _ref,
O = babelHelpers.objectWithoutProperties(_ref, ["a"]);
var c = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : O;
});
Additional context/Screenshots This issue is discovered when I am investigating #11278.
Issue Analytics
- State:
- Created 4 years ago
- Comments:5 (2 by maintainers)
Top GitHub Comments
This issue seems interesting, I’ll try fixing it.
@TrejGun I think the 0 is actually a capital-O. Maybe a different letter should be used, to make it less confusing.
i mean part
{a, ...0}
,0
(zero) a not valid name for variable. in other words you can’t doconst 0 = 0
why it should be possible with destruction?