title: How do I create a type from a string array in TypeScript?
body: <p>What is the best way of making a TypeScript type based on an array of strings? I am on version 2.6.2. The array is long and I do not want to repeat myself by duplicating the string values in an Enum declaration.</p>
  
  <p>What I want to do is something like this:</p>
  
  <pre><code>const colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];
  export type Color = convertStringArrayToType(colors);
  </code></pre>
  
  <p>The following solution <a href="https://basarat.gitbooks.io/typescript/docs/types/literal-types.html" rel="noreferrer">(source)</a> works fine, but feels hacky:</p>
  
  <pre><code>/** Utility function to create a K:V from a list of strings */
  function strEnum&lt;T extends string&gt;(o: Array&lt;T&gt;): {[K in T]: K} {
    return o.reduce((res, key) =&gt; {
      res[key] = key;
      return res;
    }, Object.create(null));
  }
  
  /**
    * Sample create a string enum
    */
  
  /** Create a K:V */
  const Direction = strEnum([
    'North',
    'South',
    'East',
    'West'
  ])
  /** Create a Type */
  type Direction = keyof typeof Direction;
  </code></pre>