2

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 a Date anymore
  • restored.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?

J0hj0h
  • 894
  • 1
  • 8
  • 34
  • Take a look at my answer for https://stackoverflow.com/questions/16261119/typescript-objects-serialization/52237888#52237888 – AQuirky Sep 08 '18 at 18:30

1 Answers1

0

Just look at generated code. TypeScript class is compiled to JavaScript class. There is no any type information at runtime, so your question not about TypeScript, but about JavaScript. Libraries uses decorators, because decorators provide some type information at runtime.

The only way is to use static analysis. For example, run Typedoc with flag --json, parse output and generate some type info for serialization purposes.

Pavel
  • 2,602
  • 1
  • 27
  • 34
  • Thanks for your answer! It's not very satisfying, but I understand a bit more clearly where the problem lies. – J0hj0h Mar 03 '18 at 20:59