I'm having trouble storing a complex TypeScript object into the browser's storage, because it has to be serialized to a JSON string.
class ComplexObject {
constructor(
public date: Date,
public child: SimpleObject,
) {}
getContent() {
return this.child.content
}
}
class SimpleObject {
constructor(
public content: string,
) {}
}
While const store = JSON.stringify(new ComplexObject(new Date(), new SimpleObject('test')))
produces JSON I am fine with, const restored = JSON.parse(store)
will be a completely different object.
restored.date
is a string, not aDate
anymorerestored.getContent()
produces a type error, as the function does not exist ob the object anymore
Current Workarounds
I have tried some serialization libraries such as cerialize, which I have gotten to work. But all the libraries I have found require explicit marking of properties or at least classes with decorators such as @Serialize()
.
This boilerplate troubles me, since I believe that TypeScript already posses all the information necessary to serialize and properly deserialize objects to JSON. Every line I have to add manually increases the potential for stupid bugs and is just plain not fun.
Question
Are there libraries that do not require manual decorators but simply take a TypeScript object, do their thing to serialize it into a JSON string, and then offer a way of restoring the proper object from that string?
If no, why is it so hard to utilize TypeScript's information? What is the core difficulty?