title: Typescript: Can you get a return type of a function based on the value of a single key in a parameter object?
body: <p>I have this hook that makes an api call and caches an object used throughout my app.</p>
  <p>Rather than need to have a bunch of helper functions to get specific values off this object id like to pass in the key of the object and get that key value returned, the hook also has access to an array of these objects and can select a specific one, or it returns the default for the app.</p>
  <p>The hook functions, I am not struggling with writing a type definition that fits the input and output in typescript.</p>
  <p>Here is what I have so far:</p>
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>type OddParams = {
      thing: number;
      thing2: number;
      key?: PotatoKey;
  }
  
  type Banana = {
      id: string;
      name: string;
  }
  
  type Potato = {
      id: string;
      name: string;
      phone: number;
      monkey: Banana;
  }
  
  type PotatoKey = keyof Potato;
  type Params = OddParams | PotatoKey;
  
  type ObjectType&lt;T&gt; = 
      T extends unknown ? Potato :
      T extends 'id' | 'name' ? string :
      T extends 'phone' ? number :
      T extends 'monkey' ? Banana :
      never;
  
  function getPotato&lt;T extends Params&gt;(desc =  (undefined as unknown) as T): ObjectType&lt;T&gt;{
      console.log(desc);
      return '2' as any
  };
  
  getPotato() //returns type Potato (returns the default potato in implemntation )
  getPotato('id') //returns type string (would return id of the default potato in implemntation )
  getPotato({thing: 2, thing2: 1, key: 'id'}) //returns type string (would return id of potato[2][1] in implemntation )</code></pre>
  </div>
  </div>
  </p>
  <p>Still need to add in the object part into the ObjectType variable.
  Also looking for better ways of declaring based on the key even when its just the string param. Above I do <code>T extends 'id'</code> and so forth for each key, but in the production problem there are 20+ keys so having a bunch of ternary for each return type is extremely unreadable in the end.</p>
  <p>Any ideas in how to achieve this?</p>