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.

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

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.