0

I am trying to add a method which would belong to a class extending Arrays of device with Typescript (3.7.5).

export class devices extends Array<device> {
    constructor(items?:Array<device>) {
        super(...items);
    }

    getDeviceByUid(uid: number): device {
        return this.filter(elmt => elmt.uid == uid)[0];
    }
}

But I also need to be able to declare and define an empty array, like I would do with a normal array:

unfilteredDeviceList: devices = []; //error : Property 'getDeviceByUid' is missing in type 'undefined[]' but required in type 'devices'.

So I tried like so: unfilteredDeviceList: devices = new devices();

I get no compile time errors when doing the latest, but in runtime : Error: Uncaught (in promise): TypeError: super is not iterable (cannot read property Symbol(Symbol.iterator))

What is the way to declare and define an extended empty array, or what should I change in the constructor?

2 Answers 2

1

Changing the constructor implementation this way should work:

class devices extends Array<device> {
    constructor(items?:Array<device>) {
        super();

        if (items) {
            this.push(...items);
        }
    }

    getDeviceByUid(uid: number): device {
        return this.filter(elmt => elmt.uid == uid)[0];
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, it works, however now I'm getting TypeError: Found non-callable @@iterator when using it in Angular. It seems that Angular passes a number to the constructor when doing some refreshes... I don't understand why
1

Guess you now initialize by const arr: devices = new devices([])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.