title: Typescript - With Array<T>, how to dynamically determine and create new instance of T?
body: <p>I have a bunch of typed Arrays of different objects. I want to write a function that adds a new blank object to the array that will work with any array as long as the type has an empty constructor. </p>
  
  <p>I'm new to Angular 2 and Typescript. The arrays are part of a form and I want to be able to add a new row/object, however I have many arrays and would appreciate a generic function for all of them.</p>
  
  <pre><code>someObject {
      constructor() { this.someField = ""; ... }
      someField: string;
      ...
  
  }
  
  someOtherObject {
      constructor() { this.someOtherField = ""; ... }
      someOtherField: string;
      ...
  }
  
  Array&lt;someObject&gt; someArray = someObject[{...}, {...} ...];
  Array&lt;someOtherObject&gt; someOtherArray = someOtherObject[{...}, {...} ...];
  
  
  // What I would like, that would work with either above array
  // new T() obviously doesn't work however
  
  addRow&lt;T&gt;(array:Array&lt;T&gt;) : void {
      array.push(new T());
  }
  </code></pre>
  
  <p>There is <em>instanceOf</em> to determine whether an object is some class. However, I haven't found a way to access the type as an object of an Array. </p>
  
  <p>I can probably use the code below BUT sometimes the array may be empty and this won't work - however it will still be typed to  so in theory we should still be able to create it.</p>
  
  <pre><code>if(array.length &gt; 0 &amp;&amp; array[0] instanceOf(someObject)) { 
      array.push(new someObject()); 
  } 
  // else if instance of someOtherObject... so on so forth
  </code></pre>
  
  <p>Is there a better way of achieving what I want, or a method I'm unaware of? Thank you.</p>
  
  <p><strong>EDIT:</strong> As Alexander said, you can dynamically do this in Typescript by using </p>
  
  <pre><code>addRow&lt;T&gt;(array:Array&lt;T&gt;, c: {new(): T}) : void {
      array.push(new c());
  }
  
  addRow(someArray, someObject);
  addRow(someOtherArray, someOtherObject);
  </code></pre>
  
  <p><em>This doesn't work when used in the HTML</em>
  e.g. <code>&lt;div class="btn btn-default" (click)="addRow(someArray, someObject)"&gt;&lt;/div&gt;</code> <strong>won't work</strong> as the HTML doesn't know about the someObject class definition.</p>