title: TypeScript Serialization
body: <p>I'm having trouble storing a complex TypeScript object into the browser's storage, because it has to be serialized to a JSON string.</p>
  
  <pre><code>class ComplexObject {
    constructor(
      public date: Date,
      public child: SimpleObject,
    ) {}
  
    getContent() {
      return this.child.content
    }
  }
  
  class SimpleObject {
    constructor(
      public content: string,
    ) {}
  }
  </code></pre>
  
  <p>While <code>const store = JSON.stringify(new ComplexObject(new Date(), new SimpleObject('test')))</code> produces JSON I am fine with, <code>const restored = JSON.parse(store)</code> will be a completely different object.</p>
  
  <ul>
  <li><code>restored.date</code> is a string, not a <code>Date</code> anymore</li>
  <li><code>restored.getContent()</code> produces a type error, as the function does not exist ob the object anymore</li>
  </ul>
  
  <h2>Current Workarounds</h2>
  
  <p>I have tried some serialization libraries such as <a href="https://github.com/weichx/cerialize" rel="nofollow noreferrer">cerialize</a>, 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 <code>@Serialize()</code>.</p>
  
  <p>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.</p>
  
  <h2>Question</h2>
  
  <p>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?</p>
  
  <p>If no, why is it so hard to utilize TypeScript's information? What is the core difficulty? </p>