【问题标题】:Why inheriting from Array not working in TypeScript?为什么从 Array 继承在 TypeScript 中不起作用?
【发布时间】:2019-03-19 17:04:39
【问题描述】:

我尝试从Array 继承,但instanceof 不起作用。

class MyList<T> extends Array<T> {}

const l = new MyList<string>()
console.log(l instanceof MyList)  // false <- WRONG
console.log(l instanceof Array)   // true

【问题讨论】:

标签: typescript


【解决方案1】:

感谢@jcalz,代码如下,more details

class MyList<T> extends Array<T> {
    constructor() {
        super()
        Object.setPrototypeOf(this, MyList.prototype)
    }

}
const l = new MyList<string>()
console.log(l instanceof MyList)  // false <- WRONG
console.log(l instanceof Array)   // true

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-11
    • 1970-01-01
    • 2015-02-12
    • 1970-01-01
    • 1970-01-01
    • 2014-06-09
    相关资源
    最近更新 更多