问题描述
我在使用instanceof运算符时遇到问题,它似乎不起作用。这是我的代码的一部分:
I'm having issues using the instanceof operator and it doesn't seem to work. Here is a part of my code:
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;
});
我的所有日志都为false,这是控制台的样子:
All of my logs say false, here is what the console looks like:
尽管明确指出只有3种类型,但都不匹配。您还可能看到对象本身带有目标类型名,所以我不明白为什么它与目标实例不匹配。
None of them match, despite being explicit that only the 3 types would be possible. You could also see the object itself with a typename of Goal, so I don't get why it doesn't match with instanceof Goal.
有什么想法吗?
推荐答案
instanceof
仅在与之匹配的函数或类匹配时返回true建造了。 项目
是简单的对象
。
instanceof
will return true only if it matches the function or class from which it was constructed. The item
here is a plain 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将按预期工作:
If it is constructed using a constructor function or a class, then instanceof will work as expected:
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
如果 Goal
为接口
只会检查对象的结构而不是类型。如果 Goal
是构造函数,则对于 instanceof
支票应返回true。
If Goal
is an Interface
it will only check the structure of the object not its type. If Goal
is a constructor then it should return true for instanceof
checks.
尝试类似以下操作:
// interface Goal {...}
class Goal {...} // you will have to change the way it works.
items = [
new Goal()
];
这篇关于TypeScript instanceof不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!