title: TypeScript: how to determine default value for generic type
body: <p>I was wondering if someone can help me with the following. I implemented a TypeScript static extension for creating an instance of a multidimensional array with an arbitrary number of dimensions (see code below), which I can use as follows:</p>
  
  <pre><code>var mat = Array.create&lt;number&gt;([2, 3]);
  mat[1][2] = 42; // the other 5 entries are undefined
  </code></pre>
  
  <p>Sofar the extension works fine. What I would like to achieve in addition, is that all entries get a default value that is depending on the actual value of the generic type parameter. For <strong>number</strong> it would be 0, for <strong>String</strong> it would be "" and for <strong>boolean</strong> it would be false (like default(T) in C#, for which unfortunately there is no TypeScript equivalent). I made various attempts to achieve this, and finally ended up with the solution as shown in the code. But unfortunately this does not work: all entries remain undefined. Does anyone have a suggestion? </p>
  
  <p>Thanks in advance -- <em>John Pool / Amsterdam / Netherlands</em></p>
  
  <pre><code>interface ArrayConstructor
  {
    create: &lt;T&gt;(dimensions: number[]) =&gt; Array&lt;T&gt;
  }
  
  Array.create = function &lt;T&gt;(dimensions: number[])
  {
    let k = dimensions[0];
  
    if (dimensions.length == 1)
    {
      // the code fragment below does not work as I hoped &amp; expected
      let t: T;
      var z: any;
  
      if (typeof t == "string")
        z = "";
      else if (typeof t == "number")
        z = 0;
      else if (typeof t == "boolean")
        z = false;
      // -----------------------------------------------------
  
      return (Array&lt;T&gt; (k)).fill (z);
    }
  
    let result = Array (k);
  
    for (var i = 0; i &lt; k; i++)
      result [i] = Array.create (dimensions.slice (1)); // create the sub-arrays
  
    return result;
  }
  </code></pre>