网站搜索

Typescript 类型转换中缺少预期的属性


在这个 playground 示例中,我正在尝试将一个对象字面量强制转换为具有属性的对象。但这并没有按预期工作。

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>");

在类型转换中有没有我遗漏的东西以让它工作,还是我应该像我对 const c=Object.assign(new X(), { y: 'ham' }); 所做的那样使用 Object.assign?

答案#1

我是否应该像我对 const c=Object.assign(new X(), { y: 'ham' }); 那样使用 Object.assign?

是的。

理想情况下,你应该在构造函数中接受它:

class X {
    constructor(public y: string){}
    get hi(): string {
        console.log(this);
        return `hi ${this.y}`;
    }
}

Object.assign 和类实例 不太兼容。仅将其用于 对象字面量。