2016-12-24 16 views
0

我有代碼(見註釋):意外錯誤TypeScript忽略表達式if(object instanceof SomeClass)``inside'for(){}`?或不?

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

這是一個錯誤?

回答

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