[Vuejs]-Typescript: class extending Array, can't assign method

3👍

The problem is how you create instances of AudioArray:

static fromArray(array: Array<number>): AudioArray {
    return array.map((v, i) => [i, v]) as AudioArray;
}

The fact that you use as cast to silence the compiler does not make the result of array.map an instance of AudioArray (that is, does not set prototype chain). You need to use a proper constructor to do that.

class AudioArray extends Array<[number, number]> {
    constructor(size: number) {
         super(size);
    }

    static fromArray(array: Array<number>): AudioArray {
        const ret = new AudioArray(0);
        ret.push(...array.map((v, i) => AudioArray.toRecord(i, v)));
        return ret;
    }

    static toRecord(a1: number, a2: number): [number, number] { 
        return [a1, a2];
    }

    addNumber(num: number): AudioArray {
        const ret = new AudioArray(0);
        ret.push(...this.map((x: [number, number]) => AudioArray.toRecord(x[0], x[1] + num));
        return ret;
    }
}

More generally, extending Array to add methods is questionable design, think if you can achieve your goal using composition.

👤Lesiak

Leave a comment