David Thielen David Thielen - 1 month ago 9
TypeScript Question

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

Answer

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.