Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement a "ArrayLike" class in TypeScript?

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
}

like image 845
yaquawa Avatar asked Mar 23 '26 10:03

yaquawa


1 Answers

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.

Playground link to code

like image 85
jcalz Avatar answered Mar 26 '26 10:03

jcalz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!