Imagine a scenario with a class structured like this:
class Individual {
private _name: string;
get Name(): string { return this._name; }
set Name(name: string) { this._name = name; }
}
Upon invoking
HttpClient.get<Individual>()
, it retrieves an object of type Individual
but fails to trigger the setter for the object's properties.
An example illustrating this issue is that when casting, the setter is not executed, unlike regular object creation: https://jsfiddle.net/r175sLkh/
The underlying reason appears to be that during conversion from a JSON string, an anonymous object is first created and then cast into the desired object. In cases where there is a setter for a property, it gets overwritten by the basic type from the JSON object.
Therefore, the original Individual.Name()
will be replaced by (anonymous).Name
due to having the same name.
To ensure my setter functions as intended, I would need to manually iterate over the result from
HttpClient.get<Individual>()
and assign each property individually to a new instance of Individual
...
So my query now is:
Is there a more efficient method to guarantee that a setter is activated when casting into the desired object without the need for manual conversion or assignment? (This inquiry does not focus on getter/setter functionality in TypeScript.)