I want to make a class based on an array with an added get method that implements a circular reference. Initially, the code looked like this:

 export class CircularArray extends Array<string> { constructor(data: string[]) { super(); this.push(...data); } get(i: number): string { return this[i % this.length]; } } 

And in the version 2.0.10 type script everything worked. However, when I decided to update the script script to the current version 2.2.0, it turned out that the code began to be compiled differently , namely, the constructor appeared processing the value returned from the super() call:

 function CircularArray(data) { var _this = _super.call(this) || this; _this.push.apply(_this, data); return _this; } 

This causes the object created by the call to Array() to be returned. Naturally, its prototype is Array.prototype , not CircularArray.prototype , so my get method is lost. How to solve this problem?

Trying to do something like this:

 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]; }; 

But I get a logical set of errors:

error TS2300: Duplicate identifier 'CircularArray'.
error TS2300: Duplicate identifier 'CircularArray'.

PS: This question is in English

  • Well, don’t write that your function returns CircularArray if it doesn’t return anything :) - Grundy
  • @Grundy, I already fixed it. The main problem is that the Duplicate identifier is obtained due to the function and class declaration. I do not know how to rewrite it so that it can be used in other places. - Qwertiy ♦
  • so it is, and is it necessary to do export in both places? - Grundy
  • @Grundy, so the error does not depend on export ... And it seems to be necessary? - Qwertiy ♦
  • association: stackoverflow.com/q/42345028/4928642 - Qwertiy ♦

1 answer 1

Found a way:

 export interface CircularArray extends Array<string> { constructor(data: string[]): CircularArray; get(i: number): string; } export var CircularArray: { new (data: string[]): CircularArray } = function CircularArray(data: string[]): void { this.push(...data); } as any; CircularArray.prototype = Object.create(Array.prototype); CircularArray.prototype.get = function (i: number): string { return this[i % this.length]; };