'Object assigned in base class does not change the child class
I want to create a base class with initial data like below:
export abstract class Entity {
constructor(data?) {
if (data) {
Object.assign(this, data);
}
}
}
with a child class like below:
export class Filter extends Entity{
show = true
constructor(filter?: Partial<Filter>) {
super(filter);
}
}
The issue I am facing is that when I create an object like this new Filter({show:false}), I get the following result:
Filter {show: true}
The object in base class did not reflect the values in child class. Any thoughts why is this happening?
Solution 1:[1]
It happens because you've set show variable to true in your derived class. So it overrides the value of base class. To avoid this behavior you should just delete initialization value:
export class Filter extends Entity{
show;
constructor(filter?: Partial<Filter>) {
super(filter);
console.log('Filter', this)
}
}
Solution 2:[2]
I solved by adding a setTimeOut on the Object.assing like this:
constructor (data) {
setTimeout(() => {
Object.assing(this, data)
}, 0)
}
It makes the assing at the finish of the javascript queue. Or you can make a class decorator and do your logic overriding the constructor
function DecoratorName () {
return function _DecoratorName<T extends {new (...args: any[]): {}}>(constr: T) {
return class extends constr {
constructor (...args: any[]) {
// The logic inside here executes after child declaration
// and allows get no undefined on properties on
// Object.assing use
super(...args)
Object.assign(this, args[0].data)
}
}
}
}
@DecoratorName()
class Example {
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
