You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript问题:无法通过Object.keys()访问子类属性

问题:子类属性无法在基类构造函数中被遍历

我希望将基类构造函数中定义的逻辑复用至所有子类,具体来说,想在构造函数中遍历类的所有属性。原本预期在基类构造函数中调用Object.keys(),同时子类构造函数调用super()就能实现该功能,但实际结果不符合预期。

代码示例

class BaseClass {
    private baseField1: string;
    private baseField2: string;

    constructor(data: any) {
        console.log(this.constructor.name + " has fields: " + Object.keys(this));
    }
}

class ChildClass extends BaseClass {
    private childField1: string;

    constructor(data: any) {
        super(data);
    }
}

let base = new ChildClass({name: 'Joe'});

预期输出

ChildClass has fields: baseField1,baseField2,childField1

实际输出

ChildClass has fields: baseField1,baseField2

输出中并未包含childField1属性,请问该如何解决这个问题?


解决方法(更新)

最终实现了预期效果,感谢Touffy!

class BaseClass {
    private baseField1: string;
    private baseField2: string;

    constructor(data: any) {
        Object.assign(this, data);
    }
}

class ChildClass extends BaseClass {
    private childField1: string;

    constructor(data: any) {
        super(data);
        if (data.childField1) this.childField1 = data.childField1;
    }
}

let base = new ChildClass({
    baseField1: 'bf1',
    baseFileds2: 'bf2', 
    childField1: 'Joe'
});

console.log('Class fields: ' + JSON.stringify(base));

输出结果

Class fields: {"baseField1":"bf1","baseFileds2":"bf2","childField1":"Joe"}


内容的提问来源于stack exchange,提问作者Sergei

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 19:02:11