How to extend and override array methods in typescript
now i want to implement an array proxy. here is 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 push override methods were not being called. and the variable foo is an Array instance 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 was looking for some solution but couldn't.
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 the 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 supercall in the ArrayProxy constructor. thanks to @Aluan Haddad.
source to share
Built-in subclasses are currently broken.
It is also extremely dangerous because when the code is executed in es2015 compatible environments it does not work for functions such as 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
source to share