Issue
I have an object source with no type defined, but represents a typed object. So that I'm using the Object.assign(target, source). But my class have properties which are getters (because they are results of calculations of the other properties).
An example:
source: {
a: 1,
b: 2,
sum: 3
}
class SomeClass {
a: number;
b: number;
get sum(): number {
return a + b;
}
}
someFunction() {
let obj = new SomeClass();
Object.assign(obj, source);
}
In the above situation, I get an error: Cannot set property sum of [object Object] which has only a getter.
Is there any way of the Object.assign() ignore those properties from the source object?
Solution
You can't use Object.assign()
for that, because
The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object.
In other words, Object.assign()
is driven by enumerable properties of the source
and is not affected by the way the properties are defined in the target.
You have to implement your own function instead of Object.assign()
which will skip properties that are not writable for the target, or find some library which does that.
Answered By - artem
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.