In my scenario, I have a class B
that is an extension of class A
. My intention is to duplicate all the properties of class A
onto class B
, considering that B
already has all the properties (and more) present in A
.
For instance:
class TypeA {
propX: number = 0;
propY: number = 0;
}
class TypeB extends TypeA {
propZ: number = 0;
}
let A: TypeA = {propX: 1, propY: 2};
let B: TypeB = new TypeB();
//I aim to copy the properties of A onto B at this point
Object.keys(A).forEach(prop => B[prop] = A[prop]);
//now assign a value to the unique property of B
B.propZ = 3;
//expected result {propX: 1, propY: 2, propZ: 3}
console.log(B);
The line Ojbect.keys(A) ...
was functional in a previous TypeScript version, but it now fails to compile. Even though it works well in this TypeScript playground, errors are encountered on that specific line. Moreover, in my Angular project, compilation is unsuccessful.
What would be the most appropriate way to achieve this now?
I did come across a similar question, although none of the suggested solutions seemed effective. While I couldn't fully comprehend the accepted "solution," I attempted to implement it in my code as follows:
let key: keyof TypeA;
for (key in A) {
A = {
...A,
[key]: B[key]
}
}
Although this approach seems confusing to me, I gave it a shot before seeking assistance 🤷♂️
Your insights and guidance are greatly appreciated.