Extend native JavaScript array

Starting in TypeScript 1.6, you can extend the Array type, see What’s new in TypeScript

Here’s an example:

class MyNewArray<T> extends Array<T> {
    getFirst() {
        return this[0];
    }
}

var myArray = new MyNewArray<string>();
myArray.push("First Element");
console.log(myArray.getFirst()); // "First Element"

If you are emitting to ES5 or below, then use the following code:

class MyNewArray<T> extends Array<T> {
    constructor(...items: T[]) {
        super(...items);
        Object.setPrototypeOf(this, MyNewArray.prototype);
    }

    getFirst() {
        return this[0];
    }
}

Read more about why this is necessary here.

Leave a Comment