2017-08-30 99 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 }; 
} 
相关问题