I have got this code:
var x = {
x1: 5,
x2: 7
};
var y = {
...x,
_originalX2: x.x2,
get x2() {
console.log(this.x1);
return 9;
}
};
console.log(y.x2);
var z = {
...x,
_originalX2: x.x2
};
Object.defineProperty(z, 'x2', {
get: function() {
console.log(this.x1);
return 9;
}
})
console.log(z.x2);
When I run this as JavaScript in the browser or in NodeJS, I get the output:
5
9
5
9
When I run the same code as TypeScript (see https://repl.it/repls/TornHomelyThing), I get the output:
undefined
9
5
9
I also see what JS TS generates from it @ https://www.typescriptlang.org/play/?ssl=1&ssc=1&pln=22&pc=1#code/G4QwTgBAHhC8EG8oEYBcECsAaaAmdA7AL4DcAUGaJAJ5yJkQQB0LUODEA+gPZgCWAcz4A7EABsAGvihMoudowEBTAC54AFAEoEHRgGNuwgM7cxSpmO4D1KgBZ8js5JvKNGYVQFcwwiAE5XCCIyUjIDY1NzS2tqWVwXCioIAC86HUYWWQUuXkERcSlUGTkQ8gB5ACMAKyU9FSYAEyUAMxElAAUwbgAHJTAVanVknAByORGcBAhlFXRmz2E6vkMtejcIcJMzCysbe0cUBPWPFW9fAI4iIM0wwy2o3eS4hKA .
My question is two-fold:
- Is this to be considered a bug in TypeScript given that the same code in JS has different behavior?
- Is there a good reason for the
this
not being able to reference thex1
in the TypeScript generated JS? Or, is that a bug in JS itself?