title: typescript generic function to convert any to array of any
body: <p>I want a write a simple utility function that takes any argument and if the arg is not already array return array with a single element, that arg.</p>
  <p>examples:</p>
  <pre class="lang-js prettyprint-override"><code>toArray('hey') =&gt; ['hey']
  toArray(['hey']) =&gt; ['hey'] 
  </code></pre>
  <p>implementation:</p>
  <pre class="lang-js prettyprint-override"><code>export type ToArr&lt;T&gt; = T extends any[] ? T : T[];
  export const toArray = &lt;T&gt;(arg: T): ToArr&lt;T&gt; =&gt; {
    return (Array.isArray(arg) ? arg : [arg]) as ToArr&lt;T&gt;;
  };
  </code></pre>
  <p>that's works fine, as long as the arg passed to <code>toArray</code> is not of type 'any':</p>
  <pre class="lang-js prettyprint-override"><code>type testType1 = ToArr&lt;string&gt;; // string[]    - ok
  type testType2 = ToArr&lt;string[]&gt;; // string[]  - ok
  type testType3 = ToArr&lt;any[]&gt;; // any[]        - ok
  type testType4 = ToArr&lt;any&gt;; // any            - not ok! should be any[]
  
  let myVar:any = 'test'
  let myVarArr = toArray(myVar) //               - type of myVarArr is any instead of any[]
  </code></pre>
  <p>what's wrong with my implementation of <code>toArr</code> generic? why does any extends any[] (the condition in the generic function)? how can I modify this function to handle cases where arg is of type any?</p>
  <p>for clarification: I want <code>toArray</code> will always return a value with type of array.</p>
  <pre class="lang-js prettyprint-override"><code>export type ToArr&lt;T&gt; = T extends any[] ? T : T[];
  </code></pre>