Расширяет массив в Typescript - PullRequest
2 голосов
/ 24 июня 2019

Если я попытаюсь сделать это на 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();

Функция возвращает результат _super.apply вместо this.Таким образом, я получаю массив, а не тест, унаследованный от массива.Если я изменю эту строку

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

на

        _super.apply(this, items)
        return this;

Она будет работать, как и ожидалось.Может ли это быть ошибкой в ​​Typescript из-за особой природы массива?Или что-то не так с моей реализацией?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...