【发布时间】:2018-02-08 09:07:29
【问题描述】:
我在使用 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;
});
我所有的日志都是假的,这是控制台的样子:
它们都不匹配,尽管明确表示只有 3 种类型是可能的。您还可以看到类型名称为 Goal 的对象本身,所以我不明白为什么它与 instanceof Goal 不匹配。
有什么想法吗?
【问题讨论】:
-
你是如何生成
items的?它们是通过构造函数创建的吗?如果不是,它们将不是给定类的实例。 -
您是否复制了对象?通过 JSON.parse 或 Object.assign?
-
它们是来自 API/http 调用的响应。一定是为什么他们的 typeofs 总是对象而不是特定类型?
-
@AnimaSola 对。要使
instanceof工作,您需要从构造函数中实际制作它们。否则,它们只是恰好与您想要的对象具有相同形状的对象。 -
感谢@MikeC,选择使用 hasOwnProperty。
标签: javascript typescript types casting instanceof