javascript - typescript 实例不工作

标签 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.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; 
        });

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

No type matched

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

有什么想法吗?

最佳答案

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

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

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

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

关于javascript - typescript 实例不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45964008/

相关文章:

java - 如何在jsp中添加消息框而不是新窗口

javascript - TypeScript 函数式编程模式是否能实现舒适的对象构造?

node.js - 使用 ts-node 时通过 fork() 调用子进程

c++ - 模板结构作为数组

c++ - 如何检查类型是否是 C++ 中模板类的类型参数?

javascript - Angular 不会更改 json 中的音频源

javascript - Phonegap 中的多屏支持和适用于 android、iphone、windows blackberry 的图像大小

android - 在 chrome 开发工具上模拟低分辨率设备

sql-server - 选择 SQL Server 数据类型以获得最大速度

javascript - 提醒用户 Extendscript 中数组之外的项目