In my TypeScript code, I am compiling to ES2016 and encountered a situation where I was calling two different functions with similar this
objects using Function.prototype.call()
. To merge both this
objects, I decided to use a common object and utilized the ...spread
syntax like this:
let selfShared = {
props,
// ...
};
let selfHost = {
...selfShared,
// ...
};
let selfGuest = {
...selfShared,
// ...
};
The intention behind using spread was to be able to overwrite shared properties in either of the this
objects if needed. However, when compiled by tsc
, it resulted in unexpected behavior as shown below:
let selfShared = {
props
};
let selfHost = Object.assign(Object.assign({}, selfShared), {
// ...
});
// ...
By incorporating my initial code snippet:
let state = undefined;
let attributes = {};
let selfShared = {
props: attributes
};
let selfHost = {
...selfHost,
get state() {
console.log("selfHost get state");
return state;
},
set state(originalStates) {
console.log("selfHost set state");
!state ? state = originalStates : console.error("`this.states` already defined in the host function.");
}
}
The output showed a difference between the expected result and the actual result after compilation by tsc
. This discrepancy led to different logs being displayed based on the execution environment.
Furthermore, I tried moving the spread operation to the end of the file, which produced a correct output but limited my ability to override properties from selfShared
.
If you can shed some light on why these discrepancies occur with Object.assign
and provide any tips to achieve the desired outcome after compilation by tsc
, it would be greatly appreciated.