I recently came across this intriguing playground example outlining a scenario where I attempted to convert an object literal into an object with specific properties, but encountered unexpected results.
class X {
y: string;
get hi(): string {
return `hi ${this.y}`;
}
}
const a = new X();
a.y = 'bob';
const b = { y: 'ham' } as X;
const c = Object.assign(new X(), b);
document.write(a.hi); // outputs "hi bob"
document.write("<br>");
document.write((b.hi === undefined).toString()); // yields "true"
document.write("<br>");
Object.assign(b, X.prototype);
document.write((b.hi !== undefined).toString()); // generates "true"
document.write("<br>");
document.write(b.hi); // **shows "hi defined" -- seeking "hi ham"**
document.write("<br>");
document.write(c.hi); // produces "hi ham"
document.write("<br>");
Could there be something crucial missing in the conversion process for this setup to function correctly? Or should I stick with using Object.assign
similar to how I handled it with
const c = Object.assign(new X(), { y: 'ham' });
?