title: Instruct TypeScript Which Return Type is Expected
body: <p>I have a function that can return a couple of different types and I want to specify the return using an argument:</p>
  <pre><code>
  type returnTypes = 'string' | 'object';
  
  function getValue(returnType: returnTypes): string | Record&lt;string, string&gt; {
    if(returnType === 'object') {
      return { my: 'return value' }
    }
    return 'my return value';
  }
  
  interface IData {
    myObjectValue: Record&lt;string, string&gt;;
    myStringValue: string;
  }
  const data: IData = {
    myObjectValue: getValue('object'),
    myStringValue: getValue('string'),
  }
  </code></pre>
  <p><a href="https://www.typescriptlang.org/play?#code/C4TwDgpgBAThwFcYDsAq4IGcoF4oHJNgYBLZAc3ygB8CB7AIwCsIBjYfAbgChuAzBMnYk6yKOXgA1AIYAbBBAAUcRCnSQAXLHhI0GTAEotRUhRpQASmzowAJgB4TZcgBooTigD4oAb25QoEj5lHTUMXBw8fEYWdnwDX38A7VUxHwBbEC18FV0oADc5BXwAXySygNyUAkyUvML5CC5uMu4yYAgYPmlWaABJABFpYGlEgMyAeWY2YBlGrStWGwcPV3diZ08ecZAAZQ2KOYVjA-IeMqXkIihbYektQbvcMahJ6fYjiC0JWaKlaPeHAMLiSmX2pnIn2%20Uj%20ikIp3iILKQA" rel="nofollow noreferrer">TypeScript Playground</a></p>
  <p>The assignment to <code>data</code> gets me the following errors:</p>
  <blockquote>
  <p>Type 'string | Record&lt;string, string&gt;' is not assignable to type 'Record&lt;string, string&gt;'.
  Type 'string' is not assignable to type 'Record&lt;string, string&gt;'.</p>
  </blockquote>
  <blockquote>
  <p>Type 'string | Record&lt;string, string&gt;' is not assignable to type
  'string'.   Type 'Record&lt;string, string&gt;' is not assignable to type
  'string'</p>
  </blockquote>
  <p>presumably because TypeScript thinks the return value of <code>getValue</code> is wider than the types defined in my interface.</p>
  <h2>How can I instruct TypeScript based on my <code>returnType</code> argument, which of the two return types I will receive?</h2>
  <p>(Or is there a more canonical way to do this, eg just separate into functions, if so what/how?</p>