Ani*_*ola 6 javascript types casting 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;
});
Run Code Online (Sandbox Code Playgroud)
我的所有日志都显示为false,这是控制台的样子:
尽管明确只有3种类型是可能的,但它们都没有匹配.您还可以看到对象本身的类型名称为Goal,因此我不明白为什么它与目标的instanceof不匹配.
有任何想法吗?
Gop*_*a S 13
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
Run Code Online (Sandbox Code Playgroud)
如果它是使用构造函数或类构造的,那么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
Run Code Online (Sandbox Code Playgroud)
如果Goal是,Interface它只会检查对象的结构而不是它的类型.如果Goal是构造函数,则它应该返回true以进行instanceof检查.
尝试类似的东西:
// interface Goal {...}
class Goal {...} // you will have to change the way it works.
items = [
new Goal()
];
Run Code Online (Sandbox Code Playgroud)
您还可以使用类型保护来发挥您的优势:
https://basarat.gitbooks.io/typescript/docs/types/typeGuard.html
https://www.typescriptlang.org/docs/handbook/advanced-types.html
例如,如果您在类中使用文字类型保护:
class Goal {
type: 'goal'
...
}
Run Code Online (Sandbox Code Playgroud)
那么检查就很简单:
if (item.type === 'goal') {
}
Run Code Online (Sandbox Code Playgroud)
或者你可以编写自己的类型保护:
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 };
}
Run Code Online (Sandbox Code Playgroud)
小智 0
尝试使用构造函数实例化该对象。这也发生在我身上,因为我正在手动模拟该对象以进行测试。如果您创建像下面的示例一样的项目,它应该可以工作:
item: Goal = new Goal(*item values*)
Run Code Online (Sandbox Code Playgroud)