title: Use keys of an object as union-type
body: <p>I've got a object (let it be frozen so typescript may handle its keys better):</p>
  
  <pre class="lang-js prettyprint-override"><code>const obj = Object.freeze({
      'hello': 64,
      'world': 20
  }) as {[key: string]: number};
  </code></pre>
  
  <p>Now I have a function where the user can pick values by their keys:</p>
  
  <pre class="lang-js prettyprint-override"><code>const pick = (keys: Array&lt;string&gt;): Array&lt;number&gt; =&gt; {
      const values = [];
  
      for (const key of keys) {
  
          // Check if object contains property-key
          if (!(key in obj)) {
              throw new Error(`There's no such key: ${key}`);
          }
  
          values.push(obj[key]);
      }
  
      return values;
  };
  </code></pre>
  
  <p>That's looking good so far and works flawlessly during runtime where I check if the user passed any invalid keys. But how can I tell TS that only keys from <code>obj</code> can be used?</p>
  
  <p>I could do <code>Array&lt;'hello' | 'world'&gt;</code> but I'd need to update it any time I add new properties to <code>obj</code> which is kinda annoying.</p>
  
  <p>Related questions but they all seem to use types whereas I only have a object (which can be frozen if that helps):</p>
  
  <ol>
  <li><a href="https://stackoverflow.com/questions/58338925/make-union-type-of-objects-from-type-keys">Make union type of objects from type keys</a> (He got a type, I'm with a object)</li>
  <li><a href="https://stackoverflow.com/questions/58749772/get-union-type-of-object-keys-filtered-by-type-of-object-value">get union type of object keys filtered by type of object value</a> (Basically the same as 1. but he wants the <code>type</code> whereas I'm trying to build a type <em>out of</em> my object)</li>
  <li><a href="https://stackoverflow.com/questions/58474456/get-keys-of-union-of-objects-in-typescript">Get keys of union of objects in TypeScript</a> (Looks good but he also got a type...)</li>
  </ol>