title: Narrow down primitive return type of function at call site in Typescript
body: <p>Writing a function that can take an <code>any</code> value and returns only <code>boolean</code> or <code>number</code> in typescript, it all works fine, until we need to narrow down the return value of the function at the call site to suit some variable type(or parameter type in case of functions compositions)</p>
  <p>Here's the function</p>
  <pre class="lang-js prettyprint-override"><code>function parseValue(value: any, defaultValue: number | boolean): number | boolean {
  
      const valueType = typeof value;
  
  
      switch (valueType) {
          case 'undefined': {
              return defaultValue;
          }
  
          case 'boolean': {
              return value;
          }
  
          default: {
  
              if (value == 'Unlimited')
                  return Infinity;
  
              return parseInt(value);
          }
      }
  
  }
  </code></pre>
  <p>The problem is seen at call site</p>
  <pre class="lang-js prettyprint-override"><code>let booleanResult = parseValue(true, true);
  
  // Error: type boolean | number is not assignable to type boolean
  let booleanCondition: boolean = booleanResult;
  
  
  let numberResult = parseValue(2, 1);
  
  // Error: type boolean | number is not assignable to type number
  let numberValue: number = numberResult;
  </code></pre>
  <h4>Is there a way in typescript which allow us to specify the return type at call site?</h4>
  <hr />
  <p>Overloading is not compatible!
  It looks like I can't make on overload a function with different param type(correct me if I'm wrong here)</p>
  <pre class="lang-js prettyprint-override"><code>type returnType = boolean | number;
  
  // This overload signature is not compatible with its implementation signature
  
  function parseValue(value: any, defaultValue:  boolean):  returnType;
  function parseValue(value: any, defaultValue: number ): returnType{
   ...
  }
  </code></pre>
  <hr />
  <p>I know we can parse the output of the function again to make it works like:</p>
  <pre class="lang-js prettyprint-override"><code>let numberValue: number = Number(numberResult);
  </code></pre>
  <p>But I'm looking for a <code>typescript</code> solution for this problem.</p>