如何在打字稿中扩展和覆盖数组方法
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 实例。
我的打字稿version:2.3.2
tsconfig.json
{
"compilerOptions": {
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"moduleResolution": "classic",
"target": "es5",
"module": "system",
"outFile": "js/test.js"
}
}
我的测试
我寻找一些解决方案但失败了。
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
更新
当我在 ArrayProxy 的构造函数中的超级调用之后添加 Object.setPrototypeOf(this, ArrayProxy.prototype);
时,它起作用了。感谢@Aluan Haddad。
子类内置函数目前已损坏。
这也是非常危险的,因为当代码在符合 es2015 的环境中执行时,它会因 Map
.
等函数而失败
使用组合并避免这些技巧。
现在我想实现一个数组代理。这是我的代码
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 实例。
我的打字稿version:2.3.2
tsconfig.json
{
"compilerOptions": {
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"moduleResolution": "classic",
"target": "es5",
"module": "system",
"outFile": "js/test.js"
}
}
我的测试
我寻找一些解决方案但失败了。
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
更新
当我在 ArrayProxy 的构造函数中的超级调用之后添加 Object.setPrototypeOf(this, ArrayProxy.prototype);
时,它起作用了。感谢@Aluan Haddad。
子类内置函数目前已损坏。
这也是非常危险的,因为当代码在符合 es2015 的环境中执行时,它会因 Map
.
使用组合并避免这些技巧。