Javascript TypeScript实例不工作

Javascript TypeScript实例不工作,javascript,typescript,types,casting,instanceof,Javascript,Typescript,Types,Casting,Instanceof,我在使用instanceof操作符时遇到问题,它似乎不起作用。以下是我代码的一部分: const results = _.map(items, function(item: Goal|Note|Task, index: number) { let result = {}; if (item instanceof Goal) { result = { id: index, title: item.na

我在使用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; 
        });
我的所有日志都显示为false,以下是控制台的外观:

它们都不匹配,尽管明确表示只有3种类型是可能的。您还可以看到对象本身的typename为Goal,因此我不明白为什么它与instanceof Goal不匹配


有什么想法吗?

尝试用构造函数实例化对象。这同样发生在我身上,因为我是为了测试而手动模拟对象的。如果您像下面的示例那样创建项目,它应该可以工作:

item: Goal = new Goal(*item values*)

instanceof
仅当它与构造它的函数或类匹配时才会返回true。
这里是一个普通的
对象

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

您还可以使用类型防护装置来发挥优势:

例如,如果对类使用文字类型保护:

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 };
}

您如何生成
项目
?它们是通过构造函数创建的吗?如果不是,它们将不会是给定类的实例。您是否复制了对象?通过JSON.parse或Object.assign?它们是来自API/http调用的响应。必须解释为什么他们的类型总是对象而不是特定类型吗?@AnimaSola是的。要使
instanceof
起作用,您需要从构造函数中实际生成它们。否则,它们只是碰巧与所需对象具有相同形状的对象。感谢@MikeC,选择使用hasOwnProperty。遗憾的是,我遇到了一个使用构造函数创建的对象typeof失败的情况。记录它们将显示正确的类型,但检查仍然失败。@mcv
typeof
不会在JavaScript中提供类型,typeof仅适用于基本类型,这意味着您将获得
Object
作为任何类型检查的结果。您可能想尝试比较
obj.constructor
。这是,它解释了它是如何工作的,当然。但它并没有提供解决方案?@GopikrishnaS,这是我的一个打字错误;我的意思是
instanceof
,而不是
typeof
。在我的例子中,失败的原因是项目中存在同名的不同类,并且不知何故在该文件中导入了一个类,而不是我所指的那个类。(我已经将两个不同但相似的数据模型重构为一个明确的数据模型。)@CularBytes答案是:使用构造函数,否则instanceof将不起作用。当从API加载对象时,仍然需要设置
类型。但这是一个比其他解决方案更简单的解决方案。
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 };
}