title: TypeScript: Returned type when accessing undefined key on object is wrong?
body: <p>I noticed unexpected types when using objects with variable keys in TypeScript.</p>
  
  <p>Given the following code</p>
  
  <pre class="lang-js prettyprint-override"><code>type MyType = {
    [x: number] : number
  }
  
  const o : MyType = {
    0: 1,
  }
  
  const a = o[0]; // Return type correctly identified as number
  const b = o[1]; // Return type should be undefined and compiler should not allow this
  </code></pre>
  
  <p>I noticed that the type of an object access using <code>[...]</code> is not correctly detected when the object type is defined using the <code>[x: number]</code> syntax for variable keys.</p>
  
  <p>VSCode shows me that both <code>a</code>  and <code>b</code> have type <code>number</code>. Shouldn't the type be <code>number | undefined</code> instead because it can happen that a key is undefined? When logging <code>a</code> and <code>b</code> to the console, <code>a</code> is a <code>number</code> while <code>b</code> is <code>undefined</code>.</p>
  
  <p>The problem becomes more serious when an object of type <code>MyType</code> is passed to a function and this function accesses a key in this object and then does something like this:</p>
  
  <pre class="lang-js prettyprint-override"><code>function fun(o: MyType) : number {
     return o[10000] ?? null  // can be number or null at runtime
  }
  </code></pre>
  
  <p>No error is shown. But when the code is run, <code>o[10000]</code> is undefined and therefore the return value is <code>null</code> which is not a valid number. Imagine using this return value to perform further computations that are all based on the assumption that is is a valid number. This would lead to runtime errors that should have been detected by the compiler (if I don't understand something completely wrong, I am new to TS)</p>
  
  <p>(TypeScript used in these examples is configured by create-react-app, I did not change any settings)</p>