In an effort to reduce boilerplate in my constructors, I have an abstract class implementation that tries to set fields on the implementing class. A simplified version is below. The problem is that in the superclass constructor, the fields appear to be set, but outside of that constructor, they are undefined.
Code:
abstract class BaseClass {
constructor(args: any) {
Object.keys(args).forEach((key) => (this[key] = args[key]));
console.log("constructed", this);
}
}
class ChildClass extends BaseClass {
a: number;
b: string;
print() {
console.log(this);
}
}
const val = new ChildClass({ a: 1, b: "str" });
val.print();
The output of this code is:
constructed ChildClass { a: 1, b: 'str' }
ChildClass { a: undefined, b: undefined }
Is there any way to make it so that BaseClass's constructor sets values that are accessible from ChildClass?