Issue at hand:
I am currently facing a challenge in distinguishing between the private, public, and getter (get X()) properties within a TypeScript class.
Current Project Scenario:
Within my Angular project, I have implemented a model design pattern. For instance, a user model is structured as follows:
class UserModel extends BaseModel {
private _id: number;
get id() { return this._id; }
set id( _id: number ) { this._id = _id; }
}
When transmitting these models to the backend, I utilize JSON.stringify() which results in an object representation like the following, assuming the user id is set to 13:
{
_id: 13
}
My current objective revolves around modifying the toJSON() function within the UserModel. Rather than returning the private properties of the object, I aim to solely output the get X() variables. The anticipated outcome is as follows:
{
id: 13
}
In an attempt to fulfill this requirement, I have developed a simple function designed to retrieve all properties of an object. However, the challenge lies in achieving a distinction between the private and getter properties exclusively.
abstract class BaseModel {
public propsToObj() : {[key: string]: any} {
let ret: any = {};
for (var prop in this) {
ret[prop] = this[prop];
}
return ret;
}
}
The updated toJSON function is outlined as follows:
class UserModel extends BaseModel {
private _id: number;
get id() { return this._id; }
set id( _id: number ) { this._id = _id; }
toJSON() {
return this.propsToObj();
}
}
Consequently, the resultant JSON representation of the UserModel after stringification looks like:
{
_id: 13,
id: 13
}
To summarize, I am seeking guidance on how to determine the visibility and nature (getter or standard variable?) of properties within a class. Any insights on how I can achieve this goal would be greatly appreciated.