title: Variable set in forEach loop getting wrong type
body: <p>When setting a variable from inside a <code>forEach</code> callback function, that variable's type doesn't seem to come out right. A simple example:</p>
  <pre><code>let foo: (string | null) = null;
  
  [1,2,3].forEach((i) =&gt; {
    foo = &quot;bar&quot;;
  });
  
  if(foo == null) {
      throw new Error(&quot;not found&quot;)
  }
  
  # Typescript complains that `length` is not a property of type `never`
  console.log(foo.length)
  </code></pre>
  <p><a href="https://www.typescriptlang.org/play?ts=4.2.3#code/FAGwpgLgBAZg9nKBeKA7AriEBuYwDaAjADQBMxAzALoB08ATgKICGAxgBYAUnAlgJTIAfFADewKLATIoAIgBGzejNwBfPrmA8YneIiQoMWAWIkSI7enADuaMDcb1L9TjNRxo8dKgAmMvsBU8VjhUAGc4cBoQOABzHQQosFQY8z4gA" rel="nofollow noreferrer">Typescript Playground link</a></p>
  <p>Right after the <code>forEach</code> I'd expect the type of <code>foo</code> to be <code>string | null</code>, but it's actually just <code>null</code>.  By the <code>console.log</code> line I'd expect it to be just <code>string</code>, but it's actually <code>never</code> (since we've eliminated <code>null</code> as a possibility with the <code>Error</code> throwing.</p>
  <p>Importantly, the above code (minus the <code>: (string | null)</code> bit) works perfectly fine in plain JavaScript - this is purely a case of me and the TypeScript compiler not communicating properly somehow.</p>
  <p>So anyway:</p>
  <ol>
  <li>I'd love it if someone could explain why this is so that I can understand Typescript better and</li>
  <li>How do I get around this?  I can just slap a <code>foo = foo as string</code> just before the console.log, but surely there's a better way?</li>
  </ol>