title: Typescript Cast JSON to Object after a fetch with parsed dates
body: <p>I have the following type of object on my client side (typescript):</p>
  <pre><code>interface Example {
      id: number;
      name: string;
      createdOnDate: Date;
  }
  </code></pre>
  <p>I'm fetching data from the server that matches the type (same property names):</p>
  <pre><code>async function fetchExamples(): Promise&lt;Example[]&gt; {
      const response = await fetch(&quot;/example/index&quot;);
  
      if (!response.ok) {
          throw Error(&quot;...&quot;);
      }
  
      return (await response.json()) as Example[];
  }
  </code></pre>
  <p>The problem is that, the <code>createdOnDate</code> is returned from the server as a string in an ISO format (such as <code>2019-01-01T14:30:39.0000000Z</code> for example). As you can guess, the <code>createdOnDate</code> on the client doesn't get parsed to a <code>Date</code>, but it remains a string.</p>
  <p>Is there a way to cast it automatically without iterating through all of the response data. I have the following, which works as expected:</p>
  <pre><code>function parseDateFromServer(date: string): Date {
      if (date) {
          return typeof date === &quot;string&quot; ? new Date(date) : date;
      }
  
      return null;
  }
  
  async function fetchExamples(): Promise&lt;Example[]&gt; {
      const response = await fetch(&quot;/example/index&quot;);
  
      if (!response.ok) {
          throw Error(&quot;...&quot;);
      }
  
      const data = await response.json();
  
      const parsedData: Example[] = data.map(
          (x) =&gt;
              ({
                  ...x,
                  createdOnDate: parseDateFromServer(x.createdOnDate)
              } as Example)
      );
  
      return parsedData;
  }
  </code></pre>
  <p>I was wondering if I can do it in a more &quot;elegant&quot; way (also I have this code throughout my codebase, I'd rather not go and change it everywhere and my real types are quite more complex than this example one).</p>