title: Typescript - Class instance which implements generic type
body: <p>I have a function which creates a class using a generic interface. The properties of the instance are set by a parameters of that generic, like this:
  </p>
  
  <pre><code>const ClassFactory = &lt;T&gt;() =&gt; {
  
      class MyClass {
          constructor(data: T) {
              for (const key in data) {
                  if (!data.hasOwnProperty(key)) { continue; }
                  (this as any)[key] = data[key];
              }
          }
  
          // other methods can be here
      }
  
      return MyClass;
  }
  
  const GeneratedClass = ClassFactory&lt;{ id: number }&gt;();
  
  const myInstance = new GeneratedClass({ id: 1 });
  
  console.log((myInstance as any).id); // logs 1
  
  </code></pre>
  
  <p>This runs as intended, however there are 2 problems</p>
  
  <ol>
  <li><code>myInstance</code> typings doesn't have the keys of T - I'm expecting <code>myInstance.id</code> to be a number</li>
  <li>I have to cast <code>this as any</code> in the constructor to assign the values by the given data</li>
  </ol>
  
  <p>In an attempt to fix the first problem I've tried various things I've seen from other posts, including
  <code>class MyClass implements T</code>, but they all result in the same error: <code>A class can only implement an object type or intersection of object types with statically known members.ts(2422)</code>.
  I understand why it happens, however since <code>T</code> is known when defining the Class, is there a way for this to work?</p>
  
  <p>If I have the data in a <code>public data: T</code> property, then <code>myInstance.data.id</code> is properly typed. So my question is, can this be done by skipping the <code>.data</code> part?</p>
  
  <p>Thanks in advance</p>