I have a list class that looks like this:
class List<T> {
private _array: Array<T>;
constructor() {
this._array = new Array<T>();
}
get count() { return this._array.length; }
public add = (state) => {
this._array.push(state);
}
...
}
And I would like to access the internal array from the class:
var something = list[0];
In c# I would do it something like this:
public T this[int index]
{
get
{
return _array[index];
}
private set {}
}
}
But I can't see anyway to accomplish this in TypeScript. Is there a way to add array accessors to my class so it looks more like a generic List ?
Thanks for the brainpower!
You can though the syntax is a bit weird. Note that since typescript gets compiled to js, only numbers and strings are valid keys:
interface IList<T> {
[index: number]: T
}
interface IMap<T> {
[index: string]: T
}
interface IMap<K, V> {
[index: K]: V // Error: Index signature parameter type must be either string or number
}
There's a trick to it though. You can't actually overload the operator, you can only tell the compiler that it exists. For instance if you have a generic object that you wish to use as a hashtable - declare it as Map<T>
instead of any
. The same goes for arrays.
The only possible way to actually put the operator in good use is to use an array or object as the underlying element, declare them as IList/IMap
and then fiddle with their properties / prototype to add specific functionality. For example, to create an observable array see this answer
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With