TypeScript 忽略 `for(){}` 中的表达式 `if (object instanceof SomeClass)`?或不?

TypeScript ignore expression `if (object instanceof SomeClass)` inside `for(){}`? Or not?

我有代码(见评论):

class ClassA
{
  propA: any;
}

class ClassB
{
  propB: any;
}

function fn( arr: (ClassA | ClassB)[] )
{
  for( let element of arr )
  {
    if( element instanceof ClassA )
    {
      element.propA = true; // Work as expected

      () =>
      {
        element.propA; // Unexpected error
      }
    }
  }
}

意外错误消息:

Property 'propA' does not exist on type 'ClassA | ClassB'.

Property 'propA' does not exist on type 'ClassB'.

当我删除循环时 for(){}。按预期工作:

class ClassA
{
  propA: any;
}

class ClassB
{
  propB: any;
}

function fn( element: ClassA | ClassB )
{
  if( element instanceof ClassA )
  {
    element.propA = true; // Work as expected

    () =>
    {
      element.propA; // Work as expected
    }
  }
}

这是一个错误?

aluanhaddad - contributor TypeScript解决:

Your inner function is closing over a mutable binding that is scoped outside the if block and is thus not always going to be an instance of ClassA.

To make this work, use a const binding:

function fn(arr: (ClassA | ClassB)[]) {
  for(const element of arr) {