2016-12-24 3 views
0

내가 (설명 참조) 코드를 : 예기치 않게 오류의TypeScript는`for() {}`에서 표현식`if (object instanceof SomeClass)`를 무시합니까? 안 그래요?

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 
     } 
    } 
    } 
} 

메시지 : 내가 루프 for(){}를 제거

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

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

. 예상대로 작동 :

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 
    } 
    } 
} 

버그입니까?

답변

0

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) {