我在使用 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 不匹配。
有任何想法吗?
原文由 AnimaSola 发布,翻译遵循 CC BY-SA 4.0 许可协议
instanceof
仅当它与构造它的函数或类匹配时才会返回 true。item
这里是一个普通的Object
。如果它是使用构造函数或类构造的,那么 instanceof 将按预期工作:
如果
Goal
是一个Interface
它只会检查对象的结构而不是它的类型。如果Goal
是构造函数,那么它应该为instanceof
检查返回 true。尝试类似的东西:
2021 年更新:
最近一直在玩 Typescript,并想出了一个在 Typescript 和 JavaScript 中都能工作的更好的解决方案:
尝试类似的东西:
这里的接口和类具有相同的名称,因此它们可以用作类型和实例检查器。
更改接口
Goal
签名或类Goal
签名会抛出如下内容: