David Thielen
David Thielen

Reputation: 32926

overload [] for typescript class

I have the class:

export class ArrayList<t> {

   items:t[];
   // other stuff...
}

Is there a way to define the [] operator so I get:

var data = new ArrayList<number>();
data.add(23);
var x = data[0];

I'm 99% sure this falls in the no operator overloading category. But I'm asking on the off chance this is different.

thanks - dave

Upvotes: 1

Views: 2003

Answers (2)

jaboja
jaboja

Reputation: 2237

While there is no operator overloading per se in JavaScript (and so not in TypeScript too) yet ES6 adds Proxy objects so as long as your browser supports ES6 (transpilers won't help much) you can use them instead (although it would be something to be rather avoided if possible as could make debugging harder).

It adds also Object.defineProperty() which could be used to define object properties via getters and setters instead of values (but it is more like storing values directly on class instance what you seem to try to avoid).

On the other hand, in your case you should just use some "get" method even if what you described is somehow achievable as it would be more standard way of doing that in languages without true operator overloading. Getting elements via data.get(i) instead data[i] is well-known programming idiom while abandoning it would make illusion that you use normal array and not custom class.

Upvotes: 2

Ryan Cavanaugh
Ryan Cavanaugh

Reputation: 220964

There's no way to write a function that handles the indexing operator.

You could store items directly on to the class instance itself, but it's probably a bad idea.

Upvotes: 2

Related Questions