I'm currently grappling with some confusion surrounding serialization in TypeScript using JSON.stringify
and interfaces. My goal is to create an export format for serializing certain objects back to their server-side representation, focusing solely on base type data and excluding methods.
I've come across information suggesting that interfaces offer a convenient way to export to JSON, but I'm struggling to grasp the process.
Here's a basic example of my attempted approach:
interface PublicFoo {
name: string,
age: number
}
class Foo implements PublicFoo {
private _name : string;
private _age : number;
private _pin : number;
constructor(name : string, age : number, pin: number) {
this._name = name;
this._age = age;
this._pin = pin;
}
get name() {
return this._name;
}
get age() :number {
return this._age;
}
get pin() : number {
return this._pin;
}
serialize() : string {
let pubFoo : PublicFoo = this;
return (JSON.stringify(pubFoo));
}
}
My hope was that by running this code:
let foo = new Foo("George", 27, 3918);
console.log(foo.serialize());
I would receive output like this:
{"name":"George","age":27}
However, instead of the expected result, I got:
{"_name":"George","_age":22,"_pin":3239}
This outcome displays private field names, including those I do not wish to serialize and are not part of the PublicFoo
interface.
What is the correct approach to achieve this without manually constructing the export? The ability to simply stringify the object is appealing due to its convenience, especially when dealing with large and complex objects...