My problem:
I need to differentiate between the private, public and getter (get X()) properties of a typescript class.
My Project:
I have an Angular project, that has a model design pattern. Aka. an user model would look like this
class UserModel extends BaseModel {
private _id: number;
get id() { return this._id; }
set id( _id: number ) { this._id = _id; }
}
To send these models to the backend, I just JSON.stringify() them, which if the user id is set as 13, returns an object like this
{
_id: 13
}
Now I need to modify the toJSON() function on the UserModel, so that instead of returning the private properties of the object, I will return the get X() variables only. The output should look like this.
{
id: 13
}
I made this simple function, to retrieve all properties of an object, but this gives me the private properties and the get properties both.
abstract class BaseModel {
public propsToObj() : {[key: string]: any} {
let ret: any = {};
for (var prop in this) {
ret[prop] = this[prop];
}
return ret;
}
}
and the toJSON function looks like this
class UserModel extends BaseModel {
private _id: number;
get id() { return this._id; }
set id( _id: number ) { this._id = _id; }
toJSON() {
return this.propsToObj();
}
}
The outcome of stringify-ing the UserModel looks like this
{
_id: 13,
id: 13
}
In conclusion, I need to know the visibility and type (getter or regular variable?) of properties on a class, how would I achieve this?