打字稿实例不工作

新手上路,请多包涵

我在使用 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;
        });

我所有的日志都显示错误,这是控制台的样子:

没有匹配的类型

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

有任何想法吗?

原文由 AnimaSola 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 209
1 个回答

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

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

尝试类似的东西:

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

items = [
   new Goal()
];

2021 年更新:

最近一直在玩 Typescript,并想出了一个在 Typescript 和 JavaScript 中都能工作的更好的解决方案:

尝试类似的东西:

 interface Goal {
    getCount(): number;
}

class Goal implements Goal {
    getCount() {
        return 3;
    }
}

function getItemCount(item: Goal | Note | Task) {
    return item instanceof Goal ? item.getCount() : 'not a goal';
}

console.log(getItemCount(new Goal()));  // 3
console.log(getItemCount('goal'));      // 'not a goal';

这里的接口和类具有相同的名称,因此它们可以用作类型和实例检查器。

更改接口 Goal 签名或类 Goal 签名会抛出如下内容:

 TS2394: This overload signature is not compatible with its implementation signature.

原文由 Gopikrishna S 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题