title: Typescript generic constraint on class
body: <p>I'm trying to make a very simple Local Storage utiliy method. I want to get an entry according to a key (of course) and a specified type.</p>
  
  <p>Here is the code:</p>
  
  <pre><code>get&lt;T&gt;(key: string): T {
    const data = localStorage.getItem(key);
    const object = JSON.parse(data) as T;
    if (!object) {
      throw new Error(`Casting ${JSON.stringify(data)} is impossible`);
    }
    return object;
  }
  </code></pre>
  
  <p>As you know, the casting <code>as T</code> is not efficient enough.
  For instance, if my entry in Local Storage is &lt;'key', 10>, Then:
  <code>get&lt;NoMatterTheClass&gt;('key')</code> will return 10 as a number and won't throw the error.</p>
  
  <p>So my question is: how can I make sure that the cast is possible?
  A generic constraint ? I tried with <code>&lt;T extends (new() =&gt; T)&gt;</code> but it does not work</p>
  
  <p>Thanks for your help!</p>