2

I would like to create a custom Typescript class where I want to be able to access data via [] like:

const a = new CustomClass(1000 /* size of array */);
a[0] = 1;
console.log(a[0]);

And the class has to save the data to an internal array.

Aleksey L.
  • 35,047
  • 10
  • 74
  • 84
kirpt
  • 795
  • 11
  • 21
  • So what's the question? – Aleksey L. Jan 19 '20 at 18:30
  • How to create such a class? What should it extend or implement? – kirpt Jan 19 '20 at 18:31
  • https://www.typescriptlang.org/docs/handbook/classes.html – Aleksey L. Jan 19 '20 at 18:32
  • Why "an internal array"? Your code already works, any object can store a `0` property. – Bergi Jan 19 '20 at 18:34
  • 1
    What exactly would be custom about this class? Why would you not just use a normal array? If you can tell us about your goal, we can make more accurate suggestions. – Bergi Jan 19 '20 at 18:35
  • I want to do more things when get/set the value, like update another array, etc. – kirpt Jan 19 '20 at 18:36
  • There is no way to do this. Although, you can do what you have did above, but the a[0] will add property "0" to the object "a", it doesn't actually modify the internal array. For more info, visit [stack overflow javascript overloading](https://stackoverflow.com/questions/19620667/javascript-operator-overloading) – hrithik gautham TG Jan 19 '20 at 18:51

1 Answers1

0

Here's one option (I made the array a string array, but you could change to whatever you want, or make it a templated class).

class CustomClass extends Array<string> {

  greet() {
    return "Hello";
  }
}

const cc = new CustomClass()
cc[0] = "first";
cc[1] = "second";
console.log(cc[0]);
console.log(cc[1]);

For a templated class, it would be

class CustomClass<T> extends Array<T> 
user2740650
  • 1,723
  • 12
  • 19
  • BTW play with this code [here](https://www.typescriptlang.org/play/?ssl=8&ssc=1&pln=8&pc=39#code/PTAEEFQYwGwQwM4NAS2XUCAOBTKK4ZQAXAT11AHsAzUAKTgDc4BlKAJxS2KoCMArPDwDuACxRRRAWABQIVOhjC4pZBxxxiOACahGBUBiiUAdgmLsArlGKV2AOlAAVUTgQ5o8JG9ny4Nw1AYSh4YFABrD0oBIQQAGkMTXVEmDzgTVBNXTmJ0qA9zKxtLdhxfMAQUAFsUeHYSSiD0gHNLOGa3TGtRQ2QGZmAAYQBiYBZhFGpie1ly0AAJHFKAcnQMnAAPOCqsGA9YRAQALlmZA6RQQctzSirBrwQAHicAPlBNrSTkcHZ2FWe3gBvU6gUDNUo4YgACgAlKBgTJQaDSsQShkAESLGDBdEAblkoIAvrJiTJZMYzDwoFBQABeUAmHDCS7XWx3B6w8lQADaAAYALp00Do6godjmPFc7kARkF9PR7gp2klZ1MCEoe3swWaUOpfP5MPxqrMGpwWsoOr1ssNsiAA) – user2740650 Jan 19 '20 at 18:52