title: Typescript: type guard for whether an object property is defined, when the key is a wide type?
body: <p>I have a function that returns whether an object property is <code>undefined</code>. I need this function instead of just doing <code>obj[key] === undefined</code> because otherwise I'd sometimes get <code>Property 'foo' does not exist on type 'Bar'.</code>. It's straightforward to write the type when the property key is a literal. I.e.:</p>
  <pre><code>function hasDefinedProp&lt;
    Obj extends Partial&lt;Record&lt;string, any&gt;&gt;,
    Prop extends string,
  &gt;(
    obj: Obj,
    prop: Prop,
  ): obj is Obj &amp; Record&lt;Prop, Prop extends keyof Obj ? Exclude&lt;Obj[Prop], undefined&gt; : unknown&gt; {
    return obj[prop] !== undefined;
  }
  
  const obj: Partial&lt;Record&lt;string, number&gt;&gt; = {};
  if (hasDefinedProp(obj, 'foo')) {
      obj.foo + 1; // No error.
      obj.bar + 1; // &quot;Object is possibly 'undefined'.&quot;
  }
  </code></pre>
  <p>However, this doesn't work when the key's type is a wide type, i.e.:</p>
  <pre><code>const obj: Partial&lt;Record&lt;string, number&gt;&gt; = {};
  const key: string = '';
  if (hasDefinedProp(obj, key)) {
      obj[key] + 1; // No error.
      obj.bar + 1; // No error. Should be &quot;Object is possibly 'undefined'.&quot;
  }
  </code></pre>
  <p>Is it possible to make the type guard work for wide types?</p>