I'm wondering how to implement an ArrayLike class in TypeScript.
Anyone knows how to do this?
edited: This is the answer from @jcalz , works for me.
class FooList<T> implements ArrayLike<T> {
length: number
[n: number]: T
}
Classes are allowed to have index signatures just like any other object type. If you declare that a class has a number index signature (as required by the definition of ArrayLike<T>), then the compiler will allow you to get and set properties of the class values at numeric indices:
class FooList<T> implements ArrayLike<T> {
length: number
[n: number]: T
constructor(init: T[]) {
this.length = init.length;
for (let i = 0; i < init.length; i++) {
this[i] = init[i];
}
}
}
const fooList = new FooList(["a", "b", "c"]);
console.log(fooList.length) // 3
console.log(fooList[0]) // "a"
Note that unless you enable the --noUncheckedIndexedAccess compiler flag, the compiler will optimistically assume that there is an actual defined value at every possible numeric index, whereas in fact most such properties will be undefined:
fooList[12345].toUpperCase() // no compiler error, but
// 💥 RUNTIME ERROR! fooList[12345] is undefined
But since regular arrays also have this behavior:
const arr: string[] = ["a", "b", "c"];
arr[12345].toUpperCase() // no compiler error, but
// 💥 RUNTIME ERROR! arr[12345] is undefined
it's not really a big deal.
Iterable<T>from the text of your question, and implementingIterable<T>from scratch is fairly annoying so if you really want that you should ask about it explicitly. Also,FooListis not generic so the example doesn't compile... presumably you wantclass FooList<T>? Or isTsome specific type? Anyway if you just want to implementArrayLike<T>you can do it like this; does that meet your needs? If not what's missing?[n: number]: Tin a class definition, good to know! Thanks!Iterable<T>and to makeFooListgeneric?