title: TypeScript function's return type from argument shows wrong type
body: <p>I am trying to implement a function in TypeScript, whose return type is determined by the 2nd argument that is passed to the function.</p>
  <p>For example,</p>
  <pre><code>const a = ifNotEmpty(var1, &quot;hello&quot;); //a's type should be string
  const b = ifNotEmpty(var2, [1, 2]); //b's type should be number[]
  </code></pre>
  <p>But instead, I am getting
  a's type as &quot;hello&quot; and b's type as [1, 2]. Both constant types, hardcoded to &quot;hello&quot; and [1,2] instead of being &quot;string&quot; or &quot;number[]&quot;;</p>
  <p>Here is a screenshot of the determined types in VSCode
  <a href="https://i.stack.imgur.com/YoKbV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YoKbV.png" alt="enter image description here" /></a></p>
  <p>As you can see, the a's type is &quot;true&quot; hardcoded, instead of boolean. Is there a way to infer the 2nd parameter's type and return that type as the return type of the function, so a's type will be &quot;boolean&quot; and not &quot;true&quot;?</p>
  <p>Here is the function, what I tried to do:</p>
  <pre><code>const ifNotEmpty = &lt;U&gt;(value: any, defaultValue: U): U =&gt; {
      return value ?? defaultValue;
  };
  </code></pre>