title: Can TypeScript infer the properties of an object?
body: <p>I'm attempting to define a <a href="https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards" rel="nofollow noreferrer">user-defined type guard</a> to verify if a variable of <code>unknown</code> type has a <code>data</code> property. My code is defined below.</p>
  
  <pre class="lang-js prettyprint-override"><code>type DataObject = {
    data: string
  };
  
  function hasDataProperty(myObject: unknown): myObject is DataObject {
      return typeof myObject === "object" &amp;&amp;
          !!myObject &amp;&amp;
          typeof myObject.data === "string";
  }
  </code></pre>
  
  <p><a href="https://www.typescriptlang.org/play/?ssl=5&amp;ssc=68&amp;pln=5&amp;pc=77#code/C4TwDgpgBAIghsOB5ARgKwgY2FAvFAbwFgAoKKAEwTgC4oBnYAJwEsA7Ac1IF8BuU0gDMArm2wsA9mygALOPXiIACkwmQmoABQBbEKgzY6ogNZsJAdzYBKOrv1YcLerGr3shUuXJMIwYU2lQSAlBKDt0BzxcfAAiCQjsGKgAMmTPLwyAQkzwgxxU9IzyXIcAOjl6JEsVNQgNEE0YqkQYqxS0siLyIIgQsL0E4FLmuCjYxlZOGP4SbiA" rel="nofollow noreferrer">Try it on the Typescript Playground.</a></p>
  
  <p>If you open the playground, you'll see an error on line 8 indicating <code>Property 'data' does not exist on type 'object'.</code>, which makes sense, because I haven't verified that the <code>data</code> property exists on <code>myObject</code>.</p>
  
  <p>I've tried using both <code>"data" in myObject</code> and <code>myObject.hasOwnProperty("data")</code> to check if the property exists, but neither seem to affect TypeScript's inferred type of <code>myObject</code> to include <code>data</code>, it is still a plain <code>object</code> type.</p>
  
  <p>I could change the function signature to <code>hasDataProperty(myObject: any)</code> or use a type assertion to change the type from <code>unknown</code>, but both of those options ignore the object's actual properties, which could result in bugs in the type guard's logic.</p>
  
  <p>Is there a way to determine if <code>myObject</code> has a <code>data</code> property without the use of type assertions or <code>any</code>?</p>