TypeScript instanceof无法正常工作

问题描述 投票:5回答:3

我在使用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,这是控制台的样子:

No type matched

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

有任何想法吗?

javascript typescript types casting instanceof
3个回答
11
投票

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

如果它是使用构造函数或类构造的,那么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

如果GoalInterface,它只会检查对象的结构而不是它的类型。如果Goal是一个构造函数,那么它应该为instanceof检查返回true。

尝试类似的东西:

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

items = [
   new Goal()
];

1
投票

您还可以使用类型保护:

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

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

例如,如果您为类使用文字类型的后卫:

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

0
投票

尝试使用构造函数实例化对象。它发生在我身上,因为我手动模拟对象以进行测试。如果你像下面的例子一样创建项目,它应该工作:

item: Goal = new Goal(*item values*)
© www.soinside.com 2019 - 2024. All rights reserved.