我在使用扩展 Array 的自定义类时遇到了一些麻烦。我基本上只是想在 Array 类上添加一些辅助方法,这里我添加了一个 logMe
方法,并为数组添加了一个前缀。
class AAA extends Array {
_prefix: string;
constructor(prefix: string, values: number[]) {
console.log('AAA contructor', values);
// Use hack
// https://stackoverflow.com/questions/35673043/extending-array-from-typescript
super();
this.push(...values);
this._prefix = prefix;
}
logMe() {
console.log('The prefix is:', this._prefix);
console.log('The values are:');
this.map(x => x * 2).forEach(console.log);
}
}
这是我的测试:
const a = new AAA('PREFIX-A', [1, 2, 3]);
a.logMe();
预期结果:
AAA contructor [ 1, 2, 3 ]
The prefix is: PREFIX-A
The values are: 1, 2, 3
实际结果:
AAA contructor [ 1, 2, 3 ]
The prefix is: PREFIX-A
AAA contructor undefined
/Users/amaurymartiny/Workspaces/test-array/a.ts:7
this.push(...values);
^
TypeError: Cannot read property 'Symbol(Symbol.iterator)' of this.push
at new AAA (/Users/amaurymartiny/Workspaces/test-array/a.ts:7:10)
at AAA.map (<anonymous>)
at AAA.logMe (/Users/amaurymartiny/Workspaces/test-array/a.ts:13:41)
at Object.<anonymous> (/Users/amaurymartiny/Workspaces/test-array/a.ts:18:3)
at Module._compile (internal/modules/cjs/loader.js:688:30)
at Module.m._compile (/Users/amaurymartiny/Workspaces/test-array/node_modules/ts-node/src/index.ts:439:23)
at Module._extensions..js (internal/modules/cjs/loader.js:699:10)
at Object.require.extensions.(anonymous function) [as .ts] (/Users/amaurymartiny/Workspaces/test-array/node_modules/ts-node/src/index.ts:442:12)
at Module.load (internal/modules/cjs/loader.js:598:32)
at tryModuleLoad (internal/modules/cjs/loader.js:537:12)
这对我来说很奇怪,为什么当我调用this.map
时构造函数又被调用了?
typescript 3.1.3。节点 10.12.0。我已经实现了 this related thread .
最佳答案
试试这个。它对我有用。
class Collection extends Array<xxx> {
constructor(documents: Array<xxx> | number) {
if(documents instanceof Array) super(...documents);
else super(documents);
Object.setPrototypeOf(this, Object.create(Collection.prototype));
}
public get aMethodUsingMapAsExample(): string[] {
// this.map invokes the constructor with the length passed in as argument
var types = this.map(e => e.documentType);
types = types.sort();
return types;
}
}
说明: native 数组构造函数有2 个重载。您必须在扩展类中同时支持它们。这是因为 this.map 在幕后创建了一个新数组,从而使用数组的长度调用构造函数。
- ArrayConstructor(...items: any[]):在这里您必须调用传播运算符才能正确构造数组
- ArrayConstructor(arrayLength:数字)。在类型为 number 的对象上调用展开运算符将抛出异常。
关于javascript - TypeScript:扩展数组的自定义类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52950333/