title: Type safe deserialization in TypeScript
body: <p>I have this sample TypeScript code that is supposed to deserialize a simple JSON into an instance of class <code>Person</code> and then call <code>foo</code> method on it, but it doesn't work:</p>
  <pre class="lang-js prettyprint-override"><code>class Person {
      name!: string;
      age!: number;
  
      foo() {
          console.log(&quot;Hey!&quot;);
      }
  }
  
  fetch(&quot;/api/data&quot;)
      .then(response =&gt; {
          return response.json() as Promise&lt;Person&gt;;
      }).then((data) =&gt; {
          console.log(data);
          data.foo();
      });
  </code></pre>
  <p>The output of console show that object is in a proper shape, but it is not <em>recognized</em> as <code>Person</code>:</p>
  <pre><code>Object { name: &quot;Peter&quot;, age: 44 }
  ​
  age: 44
  ​name: &quot;Peter&quot;
  ​
  </code></pre>
  <p>Thus when it tries to call <code>foo</code> method it fails:</p>
  <blockquote>
  <p>Uncaught (in promise) TypeError: data.foo is not a function</p>
  <p> http://127.0.0.1:8000/app.js:14<br />
  promise callback* http://127.0.0.1:8000/app.js:12</p>
  </blockquote>
  <p>How can I fix it? Should I use <code>Object.assign</code> or there is another better/<em>native</em> solution?</p>
  <pre class="lang-js prettyprint-override"><code>let x = (&lt;any&gt;Object).assign(Object.create(Person.prototype), data);
  x.foo();
  </code></pre>