我想创建一个基于数组的类,并添加一个get
实现循环反转的方法。最初代码看起来像这样:
export class CircularArray extends Array<string> {
constructor(data: string[]) {
super();
this.push(...data);
}
get(i: number): string {
return this[i % this.length];
}
}
在打字稿版本 2.0.10 中一切正常。然而,当我决定将 typescript 更新到当前版本 2.2.0 时,结果发现代码开始编译不同,即super()
构造函数中出现了对调用返回值的处理:
function CircularArray(data) {
var _this = _super.call(this) || this;
_this.push.apply(_this, data);
return _this;
}
这导致返回通过调用创建的对象Array()
。自然,它的原型是Array.prototype
, 不是CircularArray.prototype
,所以我的方法get
就丢失了。如何解决这个问题呢?
我正在尝试做这样的事情:
export declare class CircularArray extends Array<string> {
constructor(data: string[]);
get(i: number): string;
}
export function CircularArray(data: string[]): CircularArray {
this.push(...data);
return this;
};
CircularArray.prototype = Object.create(Array.prototype);
CircularArray.prototype.get = function (i: number): string {
return this[i % this.length];
};
但是我得到了一组合乎逻辑的错误:
错误 TS2300:重复的标识符“CircularArray”。
错误 TS2300:重复的标识符“CircularArray”。
PS:这个问题是英文的
找到了一个方法: