TypeScript instanceof not working

拈花ヽ惹草 提交于 2019-12-01 02:12:46

问题


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

All of my logs say false, here is what the console looks like:

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.

Any ideas?


回答1:


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

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

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.

Try something like:

// interface Goal {...}
class Goal {...}        // you will have to change the way it works.

items = [
   new Goal()
];



回答2:


You can also use type guards to your advantage:

https://basarat.gitbooks.io/typescript/docs/types/typeGuard.html

https://www.typescriptlang.org/docs/handbook/advanced-types.html

For instance, if you use a literal type guard to your class:

class Goal {
 type: 'goal'
...
}

then the check is as simple as :

if (item.type === 'goal') {
}

Or you could write your own type guards:

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



回答3:


Try to instantiate the object with a constructor. It happened to me the same because I was manually mocking the object for testing purposes. If you create the item like following example, it should work:

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


来源:https://stackoverflow.com/questions/45964008/typescript-instanceof-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!