Typescript "error TS2532: Object is possibly 'undefined'" even after undefined check : <p>I'm trying to use the <code>--strict</code> option on <code>tsc</code> but I ran into the following "weird" case that I don't seem to understand.</p>

<p>If I write:</p>

<pre><code>function testStrict(input: {query?: {[prop: string]: string}}) {
  if (input.query) {
    Object.keys(input.query).forEach(key =&gt; {
      input.query[key];
    })
  }
  return input;
}
</code></pre>

<p>the compiler complains about:</p>

<blockquote>
  <p>test.ts(5,9): error TS2532: Object is possibly 'undefined'.</p>
</blockquote>

<p>(the offending line is <code>input.query[key];</code>)</p>

<p>What I don't understand is, I have already checked for undefined with the if guard on the first line of the function <code>if (input.query)</code>, so <strong>why does the compiler think it could possibly be undefined?</strong></p>

<p>I fixed this by adding another identical guard before the object access, like:</p>

<pre><code>function testStrict(input: {query?: {[prop: string]: string}}) {
  if (input.query) {
    Object.keys(input.query).forEach(key =&gt; {
      if (input.query) {
        input.query[key];
      }
    })
  }
  return input;
}
</code></pre>

<p>but I don't understand why another identical line would be required.</p>
