【发布时间】:2017-02-20 22:50:46
【问题描述】:
我想使用附加方法 get 创建一个基于数组的类。
最初我的代码是这样的:
export class CircularArray extends Array<string> {
constructor(data: string[]) {
super();
this.push(...data);
}
get(i: number): string {
return this[i % this.length];
}
}
在 typescript 2.0.10 中它运行良好。但是当我决定将 typescript 更新到实际版本 2.2.0 时,我发现此代码的编译 have changed:现在 typescript 处理从 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'。
【问题讨论】: