Linked Questions

Popular Questions

Typescript cast missing expected property in cast

Asked by At

In this playground example I'm trying to cast an object literal to an object with a property. That is not working as expected.

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); // ouputs "hi bob"
document.write("<br>");

document.write((b.hi === undefined).toString()); // outputs "true"
document.write("<br>");

Object.assign(b, X.prototype);
document.write((b.hi !== undefined).toString()); // outputs "true"
document.write("<br>");
document.write(b.hi); // **outputs "hi defined" -- want "hi ham"**
document.write("<br>");

document.write(c.hi); // outputs "hi ham"
document.write("<br>");

Is there something I'm missing in the cast to make this work, or should I just Object.assign like I'm doing with the const c = Object.assign(new X(), { y: 'ham' });?

Related Questions