Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript Array<T> inheritance

I have some experimental code that inherits from Array<T>...

class SuperArray<T> extends Array<T> {
    constructor(...items) {
        super(...items);
    }

    public clear(): void {
        while (this.length > 0) {
            this.pop();
        }
    }
}

var array = new SuperArray("Matt", "Mark", "Luke", "John");

array.clear();

Playground

I've added the clear method just to illustrate the problem. When this is compiled and run in the browser, I get...

TypeError: array.clear is not a function

How is this completely valid code in TypeScript, but not valid in JavaScript, and is there a way to fix this?

like image 716
Matthew Layton Avatar asked Sep 06 '25 03:09

Matthew Layton


1 Answers

BTW this is a breaking change in TS2.1

This TS documentation has a recommendation for a changing the prototype in your constructor

constructor(...items) {
    super(...items);
    Object.setPrototypeOf(this, SuperArray.prototype);
}
like image 76
HolgerJeromin Avatar answered Sep 07 '25 21:09

HolgerJeromin