在Typescript中扩展数组不允许我修改数组

时间:2018-02-20 17:26:45

标签: angular typescript

我创建了一个扩展Array

的类
export class Collection<T> extends Array<T> {
    constructor(items?: Array<T>) {
        super(...items);

        Object.setPrototypeOf(this, Object.create(Collection.prototype));
    }

    whereKey(key: string, value: any): T {
        for(let i = 0; i < this.length; i++) {
            if(this[i][key] === value) {
                return this[i];
            }
        }
    }

    removeAt(index: number) {
        this.splice(index, 1);
    }
}

但是,使用任何标准数组方法(如splice(),甚至filter())都不起作用。我将ImportsHomeComponent.html:15 ERROR TypeError: CreateListFromArrayLike called on non-object视为错误。从字面上看,我唯一可以使用的方法是推送。

我创建了这样的集合:

getImportTests(): Observable<Collection<ImportTest>> {
    return this.http.get<Collection<IImportTest>>(route('imports/import-tests')).map((importTests: Collection<IImportTest>) => {
        return new Collection<ImportTest>(importTests.map((importTest: IImportTest) => {
            return new ImportTest(importTest);
        }));
    });
}

然后尝试删除这样的元素:

this.importTests.removeAt(this.importTests.indexOf(importTest));

我只需要使用whereKey方法的集合,但我对任何事情持开放态度,因为这让我发疯。

1 个答案:

答案 0 :(得分:1)

Collection构造函数未正确调用超级Array构造函数。请注意结构不同:

new Collection(["a", "b"]) =>
    Array(2)0: "a"1: "b"length: 2__proto__: Collection

new Array(["a", "b"]) =>
    Array(1)0: (2) ["a", "b"]length: 1__proto__: Array(0)

试试这个:

constructor(...items) {
        super(...items);

        Object.setPrototypeOf(this, Object.create(Collection.prototype));
    }