2017-08-30 57 views
1

我遇到了使用instanceof操作符的問題,它似乎不起作用。這裏是我的代碼的一部分:TypeScript instanceof不起作用

 const results = _.map(items, function(item: Goal|Note|Task, index: number) { 
      let result = {}; 
      if (item instanceof Goal) { 
       result = { id: index, title: item.name }; 
      } else if (item instanceof Note) { 
       result = { id: index, title: item.content.text }; 
      } else if (item instanceof Task) { 
       result = { id: index, title: item.name }; 
      } 

      console.log(item); 
      console.log(item instanceof Goal); 
      console.log(item instanceof Note); 
      console.log(item instanceof Task); 

      return result; 
     }); 

我所有的日誌說假的,這裏是控制檯的樣子:,

No type matched

他們沒有匹配儘管是明確的,只有3種類型是可能的。您也可以使用目標類型名稱來查看對象本身,所以我不明白它爲什麼與目標instanceof不匹配。

任何想法?

+3

你是如何產生'items'?他們是通過構造函數創建的嗎?如果不是,它們將不會是給定類的實例。 –

+0

你有沒有複製對象?通過JSON.parse或Object.assign? – Wazner

+0

他們是來自API/http調用的響應。必須通過爲什麼他們的typeofs總是對象而不是特定的類型? – AnimaSola

回答

0

嘗試使用構造函數實例化對象。它發生在我身上的原因是因爲我爲了測試目的手動嘲笑對象。如果你創建了下面的示例中的項目,它應該工作:只有當它從它構造函數或類匹配

item: Goal = new Goal(*item values*) 
3

instanceof將返回true。 item這裏是一個普通的Object

const a = { a: 1 } // plain object 
console.log(a); 

// {a:1}     <-- the constructor type is empty 
// a: 1 
// __proto__: Object <-- inherited from 

a instanceof A   // false because it is a plain object 
a instanceof Object // true because all object are inherited from Object 

如果使用構造函數或類構造的,則的instanceof將作爲預期:

function A(a) { 
    this.a = a; 
} 

const a = new A(1); // create new "instance of" A 
console.log(a); 

// A {a:1}    <-- the constructor type is `A` 

a instanceof A   // true because it is constructed from A 
a instanceof Object // true 

如果GoalInterface它將只檢查對象不是其類型的結構。如果Goal是一個構造函數,那麼它應該爲instanceof檢查返回true。

試着這麼做:

// interface Goal {...} 
class Goal {...}  // you will have to change the way it works. 

items = [ 
    new Goal() 
]; 
0

您還可以使用型後衛,你的優勢:

https://basarat.gitbooks.io/typescript/docs/types/typeGuard.html

https://www.typescriptlang.org/docs/handbook/advanced-types.html

舉例來說,如果你使用一個文字型後衛您的課程:

class Goal { 
type: 'goal' 
... 
} 

然後檢查很簡單,只要:

if (item.type === 'goal') { 
} 

或者你也可以寫你自己的類型警衛:

function isNote(arg: any): arg is Note { 
    // because only your Note class has "content" property? 
    return arg.content !== undefined; 
} 

if (isNote(item)) { 
    result = { id: index, title: item.content.text }; 
} 
相關問題