4

now I want to implement an array proxy. here's my code

class ArrayProxy<T> extends Array<T> {

    constructor(data: T[]) {
        super(...data);
    }

    push(...items: T[]): number {
        var res = super.push(...items);
        console.log("push invoked!");
        // some code to do extra operation.
        return res;
    }
}

var foo = new ArrayProxy(["aa","bb"]);
foo.push("cc");

it seems that my override push methods was not invoked. and the foo variable is instance of Array other than ArrayProxy.
my typescript version:2.3.2
tsconfig.json

{
    "compilerOptions": {
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "moduleResolution": "classic",
        "target": "es5",
        "module": "system",
        "outFile": "js/test.js"
    }
}

MyTest
i looked for some solution but failed.

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"

from David Sherret
but i got error.

Uncaught (in promise) Error: myArray.getFirst is not a function
  Evaluating http://localhost:8080/application/test/application/ts/bind_test
  Loading application/ts/bind_test
    at Object.execute (test.js:1733)
    at j (system.js:4)
    at E (system.js:4)
    at O (system.js:4)
    at system.js:5

update it works when i add Object.setPrototypeOf(this, ArrayProxy.prototype); after the super call in ArrayProxy's constructor. thanks to @Aluan Haddad.

Community
  • 1
  • 1
Narro
  • 430
  • 5
  • 14

1 Answers1

4

Subclassing built-ins is currently broken.

It is also extremely dangerous because when the code execute in es2015 compliant environments it will fail for functions like Map.

Use composition and avoid these techniques.

See here for reference: https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work

Aluan Haddad
  • 29,886
  • 8
  • 72
  • 84