首页 > 解决方案 > 在 Typescript 中扩展数组

问题描述

如果我尝试在Typescript 操场上这样做:

class Test extends Array {
    constructor(items: number[]) {
        super(...items);
    }

    foo(): void { console.log('foo'); }
}

const t = new Test([]);
t.foo();

这不起作用。foo未定义。如果我查看生成的代码:

var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var Test = /** @class */ (function (_super) {
    __extends(Test, _super);
    function Test(items) {
        return _super.apply(this, items) || this;
    }
    Test.prototype.foo = function () { console.log('foo'); };
    return Test;
}(Array));
var t = new Test([]);
t.foo();

该函数返回结果 of_super.apply而不是this。所以我最终得到一个数组,而不是一个继承自数组的测试。如果我改变这条线

        return _super.apply(this, items) || this;

经过

        _super.apply(this, items)
        return this;

它按预期工作。由于 Array 的特殊性质,这可能是 Typescript 的错误吗?还是我的实现有问题?

标签: arraystypescriptoop

解决方案


推荐阅读