I have the following TypeScript class that contains a getter / setter:
export class KitSection {
uid: string;
order: number;
set layout(layout: KitLayout) {
this._layout = new KitLayout(layout);
}
get layout() {
return this._layout;
}
private _layout: KitLayout;
constructor(init?: Partial<KitSection>) {
Object.assign(this, init);
}
}
// I can create an instance like so:
const section = new KitSection(data);
I need to POST
this instance to my server as a JSON object to store in a MySQL database column of type: JSON
, so I figured I could do the following:
const jsonSection = JSON.parse(JSON.stringify(section))
This creates a JSON
object, but when I inspect in the console, i see my private getter/setter variable instead of the public variable in the object:
console.log(jsonSection);
///IN CONSOLE///
uid: "a"
order: 0
_layout: {_rows: Array(2), columns: 12}
I don't want to store the private variable _layout
in my database, I need to store the public counterpart defined in the getter/setter: layout
.
Next, I checked out the answer provided here: https://stackoverflow.com/a/44237286/6480913 where it suggests to add the following method to convert to JSON
:
public toJSON(): string {
let obj = Object.assign(this);
let keys = Object.keys(this.constructor.prototype);
obj.toJSON = undefined;
return JSON.stringify(obj, keys);
}
However, this returns an empty object. Upon inspection, when I console.log()
the this.constructor.prototype
, I see the all the properties of the object, but each object is kind of greyed out, so when we use Object.keys()
, I receive an empty array. Why are these constructor properties greyed out?