
[英]Typescript object extends the Array<BoxModel> can not call the inside methods anymore
[英]how to extends and override array methods in typescript
现在我想实现一个数组代理。 这是我的代码
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");
似乎没有调用我的覆盖推送方法。 并且foo变量是ArrayProxy以外的Array的实例。
我的打字稿版本:2.3.2
tsconfig.json
{
"compilerOptions": {
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"moduleResolution": "classic",
"target": "es5",
"module": "system",
"outFile": "js/test.js"
}
}
MyTest的
我寻找一些解决方案,但失败了。
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"
来自David Sherret
但我得到了错误。
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
当我添加Object.setPrototypeOf(this, ArrayProxy.prototype);
时, 更新它的工作原理Object.setPrototypeOf(this, ArrayProxy.prototype);
在ArrayProxy的构造函数中进行超级调用之后。 感谢@Aluan Haddad。
子类化内置函数目前已被破坏。
这也是非常危险的,因为当代码在符合es2015的环境中执行时,对于像Map
这样的函数会失败。
使用组合并避免这些技术。
请参阅此处以供参考: https : //github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer -工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.