I am currently working on a TypeScript class that includes a getter and setter method:
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);
}
}
// An instance can be created like this:
const section = new KitSection(data);
The task at hand is to send this instance as a JSON object with a POST
request to the server for storage in a MySQL database column of type JSON
. The initial approach was to use:
const jsonSection = JSON.parse(JSON.stringify(section))
Although this successfully creates a JSON
object, upon inspection in the console, the private getter/setter variable is displayed instead of the public variable within the object:
console.log(jsonSection);
///IN CONSOLE///
uid: "a"
order: 0
_layout: {_rows: Array(2), columns: 12}
To avoid storing the private variable _layout
in the database, it is essential to store its public counterpart defined in the getter/setter as layout
.
An alternative solution from this answer proposes adding a 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 implementation results in an empty object. Upon investigation by logging this.constructor.prototype
, all properties are visible but appear greyed out, leading to an empty array when used with Object.keys()
. The question remains - why are these constructor properties greyed out?